【问题标题】:Using a C Library in Swift Gets Unsafe Pointers在 Swift 中使用 C 库会获得不安全的指针
【发布时间】:2017-03-10 13:40:48
【问题描述】:

我看过其他答案,但它们对我来说毫无意义。

我正在尝试将此库添加到我的 Swift 项目中: http://ed-von-schleck.github.io/shoco/

我按照本教程中的第 1 步和第 2 步操作: https://medium.com/swift-and-ios-writing/using-a-c-library-inside-a-swift-framework-d041d7b701d9#.r1gi4q3ri

我可以导入 shoco 模块(耶!)

根据 API,函数应该是这样的:

size_t shoco_compress(const char * in, size_t len, char * out, size_t bufsize);

但是我的 Swift 项目会生成这个编辑器占位符

shoco_compress(in: UnsafePointer<Int8>!, len: Int, out: UnsafeMutablePointer<Int8>!, bufsize: Int)

谁能告诉我如何使用这个库在 Swift 中压缩一个字符串?

第一次使用 C,任何朝着正确方向的推动都值得赞赏。提前致谢。

【问题讨论】:

    标签: ios c swift compression


    【解决方案1】:

    您绝对应该阅读Using Swift with C API。对于您的问题,以下是完整压缩-解压缩循环的示例:

    let str = "Hello world"
    
    let inCStr = str.cString(using: .utf8)!
    
    var compressedStr = [Int8](repeating: 0, count: 128)
    let compressedStrLen = shoco_compress(inCStr, inCStr.count - 1, &compressedStr, compressedStr.count - 1)
    
    var decompressedStr = [Int8](repeating: 0, count: 128)
    shoco_decompress(compressedStr, compressedStrLen, &decompressedStr, decompressedStr.count - 1)
    
    let str2 = String(cString: decompressedStr)
    print(str2) // Hello world
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      相关资源
      最近更新 更多