0

I would like to be able to:

(1) initialize a C++ class from Objective-C
(2) call C++ function from Objective-C
(3) have the C++ class call a function in Objective-C (callback/delegate pattern)

(1) and (2) have already been implementing using this link. However, I'm unable to implement (3).

I'm creating an objective-C library for iOS that also wraps and takes advantage of a C++ library. I'm able to call C++ functions from the objective-C side; however, I'm trying to make a callback using delegation pattern from the C++ side to objective-C++. The idea here is to not push code from the C++ library into Objective-C++, but keep them separate so the original code is minimally changed. This is to say, I've already made the bridge from objective-C -> objective-C++ -> C++, but haven't implemented the callback from C++ -> objective-C++ where I can easily interact with objective-C.

Looking for a simple example of this. I'm trying to use delegate pattern or possibly blocking.

Community
  • 1
  • 1
QuintoViento
  • 198
  • 3
  • 19

1 Answers1

2

You need to use Objective-C++. So everything that interfaces between ObjC and C++ needs to be in a .mm file, not regular .m or .cpp. However, you can keep stuff out of the headers to make it usable for pure C++/ObjC callers.

To call back an ObjC method (there are no functions in ObjC, it only has C functions) you need to use ObjC++ as well, it's simply the reverse of how you call C++ from ObjC:

FooShouldCallObjCFromCpp.h

class FooShouldCallObjCFromCpp
{
public:
    void CallObjC();

protected:
    struct NSString* mObjCString;  // ObjC classes look just like forward-declared C structs.
};

FooShouldCallObjCFromCpp.mm

#import <Foundation/Foundation.h>

void FooShouldCallObjCFromCpp::CallObjC()
{
    [mObjCString appendString: @" foo"];
}

You will have to assign the initial value of the mObjCString ivar from a .mm file as well. You can also use #if OBJC and #if __cplusplus to remove code from the headers that a C++ file or an ObjC file including them mustn't see, but be careful there, as C++ reacts very badly when a method or ivar goes missing, you'll get weird memory corruption. Also be careful with redefining types. struct NSString* and @class NSString get seen as the same thing by current C++ compilers, but other stuff may get mistaken to be different types and then lead to link errors.

uliwitness
  • 8,532
  • 36
  • 58