将带有字符串参数的函数指针从 Swift 传递给 Obj C++

Passing function pointer with string parameter from Swift to Obj C++

我目前在调用我的 C++ 动态库中的函数时陷入僵局,该函数需要传递函数指针,其中该函数指针具有指向字符串的指针参数,来自 Swift 我构建的测试工具。我有一种感觉,要么我在我的测试工具中的 Obj C++ header 中的函数声明不正确,要么我没有正确格式化 Swift 中的调用。

我的 Obj C++ 库中的 header(实现在我的 .mm 文件中):

@interface Objective_CPP : NSObject
- (void)InitCppDriver:(customCallbackType)readCompleteCallback;
@end

我的桥接 header 链接到我的测试工具中的相应文件(不确定这是否等同于我的库项目中的声明):

@interface Objective_CPP : NSObject
- (void) InitCppDriver:(void (*)(const wchar_t* data))readCompleteCallback;
@end

我的库项目 (C++) 中的 customCallbackType 声明:

typedef void(*customCallbackType)(const wchar_t* json);

extern customCallbackType frReadCompleteCallback;

我的 InitCppDriver 在我的库中的实现:

@implementation Objective_CPP
- (void)InitCppDriver:(customCallbackType)readMeterComplCallback
   {
   ...
   }
@end

当我去调用我的测试工具中的 InitCppDriver 函数时 (Swift):

var ptrStr: UnsafePointer<wchar_t>?;
Objective_CPP().InitCppDriver(callBack(outString: ptrStr));
...
func callBack (outString:UnsafePointer<wchar_t>?){
   //code manipulating string here
}

我试过传递一个闭包和许多其他函数定义,但我最终得到的错误是我尝试过的所有错误的变体:

Cannot convert value of type '()' to expected argument type '(@convention(c) (UnsafePointer?) -> Void)!'

我已经能够在没有将函数指针传递给它的参数的情况下成功调用我的 InitCppDriver 函数,但我似乎无法弄清楚 syntax/setup 如何使用函数指针参数。任何关于如何做到这一点的见解都会很棒 - 我不经常在 Obj-C 或 Swift 工作,现在已经坚持这个太久了。

如果我可以提供任何其他上下文来解决这个问题,我很乐意 post 提供更多代码。

谢谢!!

您正在调用回调并尝试将 return 值(即 ())传递给 C++ 函数。您应该只说 Objective_CPP().InitCppDriver(callBack(outString:))