[英]Calling C++ method with callback from ObjectiveC
I need to call a C++ method and pass in a callback method as a parameter... from ObjectiveC method... This callback method would then be triggered multiple times in ObjectiveC... as it's a callback... and so then I need to trap that ObjectiveC callback method back as it will be called as a closure from Swift code... 我需要调用C ++方法并将回调方法作为参数传递...来自ObjectiveC方法...此回调方法将在ObjectiveC中被多次触发...因为它是回调...所以我需要捕获该ObjectiveC回调方法,因为它将作为Swift代码的闭包被调用...
This is the C++ Method Signature 这是C ++方法签名
static bool cPlusPlusMethodWithCallBack(const std::string& someText, void (*someCallback)(unsigned int) = NULL, unsigned int someNum = 0);
My Question is what should be the Block syntax of this Callback Method declared in ObjectiveC (in .mm and .h) which can then be passed as a parameter to this someCallback in C++ 我的问题是,在ObjectiveC中(在.mm和.h中)声明的此回调方法的Block语法应该是什么,然后可以将其作为参数传递给C ++中的someCallback
I am a Swift developer so bit stuck on ObjectiveC... Many Thanks 我是一名Swift开发人员,因此对ObjectiveC有点困惑...非常感谢
You can't pass an Objective-C block (or a Swift closure) as a function pointer argument like that. 您不能像这样将Objective-C块(或Swift闭包)作为函数指针参数传递。 You'll need to create a separate, standalone function, and pass that in as the callback.
您需要创建一个单独的独立函数,并将其作为回调传递。
void MyCallback(unsigned int value)
{
// ...do something...
}
And in your main code: 在您的主要代码中:
cPlusPlusMethodWithCallBack("something", MyCallback);
Now, the downside of this is that in your callback, you'll often need to reference a particular Objective-C object in order to properly handle the callback. 现在,这样做的缺点是在回调中,您通常需要引用特定的Objective-C对象才能正确处理回调。 If that's something you need with this particular callback, you'll need to save it off somewhere as a static variable so that it can be accessed from the
MyCallback
function. 如果您需要使用此特定的回调函数,则需要将其保存为静态变量,以便可以从
MyCallback
函数访问它。
Alternatively, if you have control over the cPlusPlusMethodWithCallBack
source code, you can update it to take a void *
"reference" parameter, and then supply that parameter as an argument when you call the callback: 或者,如果您可以控制
cPlusPlusMethodWithCallBack
源代码,则可以对其进行更新以采用void *
“ reference”参数,然后在调用回调时将该参数作为参数提供:
static void cPlusPlusMethodWithCallback(void (*callback)(void *ref), void *ref)
{
// ...really time consuming processing...
callback(ref);
}
Then, update your callback function: 然后,更新您的回调函数:
void MyCallback(void *ref)
{
ObjectiveCObject *obj = (ObjectiveCObject *)ref;
[obj doSomething];
}
And when you initially call the method, just pass in the object you need as the reference parameter: 最初调用该方法时,只需传入所需的对象作为参考参数即可:
cPlusPlusMethodWithCallback(MyCallback, myObjectiveCObject);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.