I'm currently at an impasse in calling a function in my C++ dynamic library that requires a function pointer to be passed, where that function pointer has a parameter of a pointer to a string, from a Swift test harness I've built. I have a feeling that either my function declaration in my Obj C++ header in my test harness is incorrect, or I'm improperly formatting the call in Swift.
The header in my Obj C++ library (implementation is in my .mm file):
@interface Objective_CPP : NSObject
- (void)InitCppDriver:(customCallbackType)readCompleteCallback;
@end
The corresponding file my bridging header links to in my test harness (unsure if this is equivalent to the declaration in my library project) :
@interface Objective_CPP : NSObject
- (void) InitCppDriver:(void (*)(const wchar_t* data))readCompleteCallback;
@end
The declaration of my customCallbackType in my library project (C++):
typedef void(*customCallbackType)(const wchar_t* json);
extern customCallbackType frReadCompleteCallback;
My implementation of my InitCppDriver in my library:
@implementation Objective_CPP
- (void)InitCppDriver:(customCallbackType)readMeterComplCallback
{
...
}
@end
When I go to call my InitCppDriver function in my test harness (Swift):
var ptrStr: UnsafePointer<wchar_t>?;
Objective_CPP().InitCppDriver(callBack(outString: ptrStr));
...
func callBack (outString:UnsafePointer<wchar_t>?){
//code manipulating string here
}
I've tried passing a closure and a number of other function definitions, but the error I end up getting is a variant of this for everything I have tried:
Cannot convert value of type '()' to expected argument type '(@convention(c) (UnsafePointer?) -> Void)!'
I've been able to call my InitCppDriver function successfully without the parameter of having a function pointer passed into it, but I cannot seem to figure out the syntax/setup of how to call that same function with a function pointer parameter. Any insight on how to do this would be great - I don't work in Obj-C or Swift often and have been stuck on this for a little too long now.
If there is any other context I can give to the issue I'll be happy to post up more code.
Thanks!!
You're invoking your callback and trying to pass the return value (which is
()
) to the C++ function. You should just sayObjective_CPP().InitCppDriver(callBack(outString:))
instead.