gpt4 book ai didi

c++ - 从 C++ 方法调用 Objective-C 方法? [2]

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:52 25 4
gpt4 key购买 nike

我发现了一个很棒的帖子 Calling Objective-C method from C++ method?

但是,我有 2 个问题,这让我很难克服这个问题:

请注意,我已对 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) 如何在 void * myObjectInstance 上调用方法...

我的意思是,我不能强制转换为 MyObject 或以其他方式让编译器知道要调用什么方法:(

2) 我如何实际使用它?

在我的例子中,假设 code.m 既有

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

我会怎么做?

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

而且在我的深层 C++ 代码中只需调用

_cWrap.MyObjectDoSomethingWith((void *)somePrameter)

我缺少一个链接,那就是如何将 C 包装函数链接到 ObjectiveC 函数:(

谢谢

最佳答案

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

为什么不呢?

您的 C++ 包装器类必须位于 Objective-C++ 文件(通常用 .mm)扩展名中。然后,因为你甚至必须在类声明中声明你的私有(private)实例变量,你需要一个私有(private)成员来保存类头中的 Objective-C 指针。这一定是纯 C++ 编译器可以理解的东西,所以你可以做的一件事是:

#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);
}

然后在.mm文件中

#import "ObjCClassHeader.h"

int CWrap::MyObjectDoSomethingWith(void *parameter)
{
return [myObjectInstance doSomethingWith: parameter];
}

__OBJC__是编译器在编译Objective-C或Objective-C++时定义的预定义宏

关于c++ - 从 C++ 方法调用 Objective-C 方法? [2],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4747137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com