EAGLView 类需要从 C 类调用成员函数而不会出现问题。然而,在 C 类中,需要调用 Objective-C 函数“[context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer*)self.layer];”,这是使用纯 C 语法无法实现的。
要混合 Objective-C 和 C ,请谨慎行事。以下是使用 C 包装函数包装 Objective-C 调用的分步方法:
创建 C 接口标头:
#include <stdio.h> // for printf #include <stdint.h> // for uintptr_t typedef uintptr_t Id; // Assume a simplified EAGLView class extern void EAGLViewDoSomethingWith(Id* poself, void *aparam); int MyObjectDoSomethingWith(void *myObjectInstance, void *parameter) { printf("C wrapper function called!\n"); // Assuming Objective-C method takes a single int argument return EAGLViewDoSomethingWith(myObjectInstance, 21); }
定义 Objective-C 类:
// MyObject.h @interface MyObject : NSObject - (int)doSomethingWith:(void *)aParameter; @end
// MyObject.mm #import "MyObject.h" @implementation MyObject - (int)doSomethingWith:(void *)aParameter { // Implement Objective-C function return 42; } @end
实现 C 类:
#include "MyObject-C-Interface.h" class MyCPPClass { public: void someMethod(void *objectiveCObject) { int result = MyObjectDoSomethingWith(objectiveCObject, nullptr); } };
PIMPL(指向实现的指针)惯用法可用于面向对象实现:
定义一个 C 接口:
#include <stdio.h> // for printf #include <stdint.h> // for uintptr_t typedef uintptr_t Id; class MyClassImpl { public: MyClassImpl() : self(nullptr) {} ~MyClassImpl() { if (self) dealloc(); } int doSomethingWith(void *parameter) { return 42; } private: Id self; void dealloc() { if (self) free(self); } }; int EAGLViewDoSomethingWith(Id* poself, void* aparam); int MyObjectDoSomethingWith(void *myObjectInstance, void *parameter) { printf("C wrapper function called!\n"); return EAGLViewDoSomethingWith(myObjectInstance, 21); }
创建 Objective-C 类接口:
@interface MyObject : NSObject - (int)doSomethingWith:(void *)aParameter; @end
创建 Objective-C 类实现:
#import "MyObject.h" @implementation MyObject { MyClassImpl* _impl; } - (int)doSomethingWith:(void *)aParameter { if (!_impl) _impl = [MyClassImpl new]; return [_impl doSomethingWith:aParameter]; } @end
实现 C 类:
#include "MyObject-C-Interface.h" class MyCPPClass { public: void someMethod(void *objectiveCObject) { int result = MyObjectDoSomethingWith(objectiveCObject, nullptr); } };
这种方法提供了一个更加隔离和灵活的解决方案,使 Objective-C 实现和 C 包装器能够在不影响 C 代码的情况下进行修改。
以上是如何从 C 成员函数调用 Objective-C 方法?的详细内容。更多信息请关注PHP中文网其他相关文章!