开发者

Calling Objective-C method from C++ method? [2]

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜