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); }
// 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
#include "MyObject-C-Interface.h" class MyCPPClass { public: void someMethod(void *objectiveCObject) { int result = MyObjectDoSomethingWith(objectiveCObject, nullptr); } };
PIMPL(指向實作的指標)慣用法可用於物件導向>
#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); }
@interface MyObject : NSObject - (int)doSomethingWith:(void *)aParameter; @end
#import "MyObject.h" @implementation MyObject { MyClassImpl* _impl; } - (int)doSomethingWith:(void *)aParameter { if (!_impl) _impl = [MyClassImpl new]; return [_impl doSomethingWith:aParameter]; } @end
#include "MyObject-C-Interface.h" class MyCPPClass { public: void someMethod(void *objectiveCObject) { int result = MyObjectDoSomethingWith(objectiveCObject, nullptr); } };
定義一個實作檔案“MyObject.mm”,在其中實例化MyObject 實例MyObject.實作 C類別:包含C 介面C 類別頭檔「MyCPPClass.h」中的頭檔並使用C 包裝器 這種方法提供了一個更隔離和靈活的解決方案,使Objective-C 實作和 C包裝器能夠在不影響 C 程式碼的情況下進行修改。
以上是如何從 C 成員函數呼叫 Objective-C 方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!