gpt4 book ai didi

swift - 如何创建一个 UnsafeMutablePointer>>

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:42 27 4
gpt4 key购买 nike

我正在使用 Swift 的 C API,对于我需要调用的方法之一,我需要给出一个

UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<Int8>>>

更多信息:

快速界面:

public func presage_predict(prsg: presage_t, _ result: UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<Int8>>>) -> presage_error_code_t

原文C:

presage_error_code_t presage_predict(presage_t prsg, char*** result);

最佳答案

通常,如果一个函数接受 UnsafePointer<T>范围那么你可以传递一个 T 类型的变量如在带有 & 的“inout”参数中.在你的情况下,T

UnsafeMutablePointer<UnsafeMutablePointer<Int8>>

这是 char ** 的 Swift 映射.所以你可以调用C函数作为

var prediction : UnsafeMutablePointer<UnsafeMutablePointer<Int8>> = nil
if presage_predict(prsg, &prediction) == PRESAGE_OK { ... }

来自Presage库的文档和示例代码我明白这会分配一个字符串数组并分配此数组的地址到 prediction 指向的变量.为避免内存泄漏,最终必须释放这些字符串与

presage_free_string_array(prediction)

为了证明这确实有效,我采取了第一个部分演示代码位于 presage_c_demo.c并翻译了它 swift :

// Duplicate the C strings to avoid premature deallocation:
let past = strdup("did you not sa")
let future = strdup("")

func get_past_stream(arg: UnsafeMutablePointer<Void>) -> UnsafePointer<Int8> {
return UnsafePointer(past)
}

func get_future_stream(arg: UnsafeMutablePointer<Void>) -> UnsafePointer<Int8> {
return UnsafePointer(future)
}

var prsg = presage_t()
presage_new(get_past_stream, nil, get_future_stream, nil, &prsg)

var prediction : UnsafeMutablePointer<UnsafeMutablePointer<Int8>> = nil
if presage_predict(prsg, &prediction) == PRESAGE_OK {

for var i = 0; prediction[i] != nil; i++ {
// Convert C string to Swift `String`:
let pred = String.fromCString(prediction[i])!
print ("prediction[\(i)]: \(pred)")
}

presage_free_string_array(prediction)
}

free(past)
free(future)

这确实有效并产生了输出

prediction[0]: sayprediction[1]: saidprediction[2]: savagesprediction[3]: sawprediction[4]: satprediction[5]: same

关于swift - 如何创建一个 UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<Int8>>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32687808/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com