1

i found a great post Calling Objective-C method from C++ method?

however, i have to 2 questions, which makes me overcoming this issue very problematic :

note that i have made a change to MyObject-C-Interface.h

#ifndef __MYOBJECT_C_INTERFACE_H__ #define __MYOBJECT_C_INTERFACE_H__ 1 struct CWrap { void * myObjectInstance; int MyObjectDoSomethingWith (void *parameter) { //how to call the //myObjectInstance->MyObjectDoSomethingWith ??? } } #endif 

1) how can i call a method on a void * myObjectInstance…

i mean, i cannot cast to MyObject or otherwise let the compiler know, what method to call:(

2) how do i actually use it?

in my, lets say code.m that has both the

#import "MyObject.h" //and #include "MyObject-C-Interface.h" 

i would do?

MyObject tmp = [[MyObject alloc] init]; CWrap _cWrap; _cWrap.myObjectInstance = (void *)tmp; //pass the CWrap to a deep C++ nest myMainCPPCode->addObjectiveCToCWrap(_cWrap); 

and than in my deep C++ code simply call

_cWrap.MyObjectDoSomethingWith((void *)somePrameter) 

iam missing a link, and thats, how to link the C wraper function to a ObjectiveC function :(

thank you

1 Answer 1

3

i mean, i cannot cast to MyObject or otherwise let the compiler know, what method to call

Why not?

Your C++ wrapper class must be in an Objective-C++ file (usually denoted with the .mm) extension. Then, because you even have to declare your private instance variables in the class declaration, you need a private member to hold the Objective-C pointer in the class header. This must be something that a pure C++ compiler can understand so one thing you could do is this:

#ifndef __MYOBJECT_C_INTERFACE_H__ #define __MYOBJECT_C_INTERFACE_H__ 1 #if defined __OBJC__ typedef id MyObjCClass; #else typedef void* MyObjCClass; #endif struct CWrap { MyObjCClass myObjectInstance; int MyObjectDoSomethingWith (void *parameter); } 

Then in the .mm file

#import "ObjCClassHeader.h" int CWrap::MyObjectDoSomethingWith(void *parameter) { return [myObjectInstance doSomethingWith: parameter]; } 

__OBJC__ is a predefined macro that is defined when the compiler is compiling Objective-C or Objective-C++

Sign up to request clarification or add additional context in comments.

2 Comments

ok, but what happens, if i cannot use .mm (objective C++), but have to use .cc (C++), how would i than call [myObjectInstance doSomethingWith: parameter] ?
@Peter Lapisu: There is a compiler flag that forces the compiler to treat a file as objective-C++ no matter what the extension. I think it is something like -x objective-c++ developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.