有一个C结构:
struct SomeStruct;
还有一个 C 函数使用这个结构作为双指针参数:
C_exampleFunction(struct SomeStruct** someClass)
我想将任何 Swift 类或对象传递给这个函数以使用它的功能。然而 Swift 端的 C 函数只接受 UnsafeMutablePointer 作为参数:
mySwiftFunction(for obj: AnyObject) {
let objUnsafeMutableRawPointer = Unmanaged.passUnretained(obj).toOpaque()
let objOpaquePointer = OpaquePointer(objUnsafeMutableRawPointer)
let someClassArg = UnsafeMutablePointer<OpaquePointer?>(objOpaquePointer)
C_exampleFunction(someClassArg)
}
即使我解除分配指针,代码也总是会产生一些内存错误。我的主要问题是如何将对象作为 UnsafeMutablePointer 添加到上面这样的 C 函数中?
我检查了这些来源(但没有运气):
- https://tech.bakkenbaeck.com/post/swift-c-interop
- https://www.sitepoint.com/using-legacy-c-apis-swift/
- https://www.uraimo.com/2016/04/07/swift-and-c-everything-you-need-to-know/#pointers-conversion
- https://developer.apple.com/documentation/swift/unsafemutablepointer
- https://swift.org/migration-guide-swift3/se-0107-migrate.html
- 如何在 Swift 中使用 UnsafeMutablePointer<OpaquePointer>? - https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis/using_imported_c_functions_in_swift
我得到的错误是:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x6ba571ac0)
感谢您的回答、反馈,尤其是您提前提供的时间。