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

Community
  • 1
  • 1
Peter Lapisu
  • 19,915
  • 16
  • 123
  • 179

1 Answers1

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

JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • 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 Jan 20 '11 at 14:11
  • 1
    @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++` http://developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/gcc-4.0.1/gcc/Overall-Options.html%23Overall-Options – JeremyP Jan 20 '11 at 14:24