简体   繁体   中英

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...

This is the C++ Method Signature

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++

I am a Swift developer so bit stuck on ObjectiveC... Many Thanks

You can't pass an Objective-C block (or a Swift closure) as a function pointer argument like that. 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. 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.

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:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM