如何创建 Swift 类型 UnsafePointer<UnsafePointer<Int8> 的实例?>!传递给 C 函数

How to create instance of Swift type UnsafePointer<UnsafePointer<Int8>?>! to pass to C function

我正在尝试从 Swift

调用 C 函数

C 函数的一个参数定义为类型:

const char * const * i_argv

在 Xcode 自动完成中将此映射到 Swift 类型:

_ i_argv: UnsafePointer<UnsafePointer<Int8>?>!

我创建此类型实例的所有尝试都失败了

我想传递两个Int8的数组

let args: [Int8] = [ 1, 1 ]

如果我直接传递这个,我会得到错误:

cannot convert value of type 'UnsafePointer<Int8>' to expected argument type 'UnsafePointer<UnsafePointer<Int8>?>'

然后我尝试将数组包装在外部 UnsafePointer

let argsp: UnsafePointer<Optional<UnsafePointer<Int8>>> = UnsafePointer(args)

但这似乎没有按预期工作并给出错误:

cannot assign value of type 'UnsafePointer<Int8>' to type 'UnsafePointer<Optional<UnsafePointer<Int8>>>'

我不知道如何用外部 UnsafePointer 包装数组的 UnsafePointer 类型

编辑:

C 项目的示例:

    #define FIB_ARG_VALUE  "40"
    const char* i_argv[2] = { FIB_ARG_VALUE, NULL };
    result = m3_CallWithArgs (f, 1, i_argv);

根据您的评论,我已设法获得 Swift 代码以使用以下参数构造进行编译(只是一个编译测试)

let argsp: [UnsafePointer<Int8>?] = [ UnsafePointer([1,2,3]), UnsafePointer("40".cString(using: String.Encoding.utf8)) ]

这仍然给出关于创建悬挂指针的警告

正如我在评论中所写,

When the argument type is UnsafePointer<UnsafePointer<Int8>?>!, you need to pass an Array of UnsafePointer<Int8>?.

在你的 re-updated 部分,你了解 部分传递一个 UnsafePointer<Int8>? 的数组,但是你没有创建数组的每个元素.

与 C 项目 中的 示例等价的 Swift 将是:

let FIB_ARG_VALUE = "40"
let result: CInt = FIB_ARG_VALUE.withCString {pointer in
    let i_argv: [UnsafePointer<Int8>?] = [
        pointer,
        nil
    ]
    return m3_CallWithArgs(f, 1, i_argv)
}

编译测试代码的正确方法应该如下所示:

let arg1: [Int8] = [1,2,3]
let arg2: String = "40"
_ = arg1.withUnsafeBufferPointer {arg1BufPtr in
    arg2.withCString {arg2Ptr in
        let argsp: [UnsafePointer<Int8>?] = [ arg1BufPtr.baseAddress,
            arg2Ptr
        ]
        //Use `argsp` inside this block.
        //...
    }
}

在这两种情况下,我假设您的 C 函数不会保留传入的指针 i_argv 以供将来使用,否则您需要进行一些修改以将内容复制到某个稳定的地址。

或者您可能需要根据实际参数或 C 函数的功能修改一些其他部分。