An EAGLView class requires calling a member function from a C class without issues. However, within the C class, the need arises to call an Objective-C function, "[context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer*)self.layer];", which cannot be achieved using pure C syntax.
To mix Objective-C and C , proceed with caution. Here's a step-by-step approach for wrapping the Objective-C call using a C wrapper function:
Create a C Interface Header:
#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); }
Define the Objective-C Class:
// 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
Implement the C Class:
#include "MyObject-C-Interface.h" class MyCPPClass { public: void someMethod(void *objectiveCObject) { int result = MyObjectDoSomethingWith(objectiveCObject, nullptr); } };
The PIMPL (Pointer to Implementation) idiom can be utilized for an object-oriented implementation:
Define a C Interface:
#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); }
Create an Objective-C Class Interface:
@interface MyObject : NSObject - (int)doSomethingWith:(void *)aParameter; @end
Create an Objective-C Class Implementation:
#import "MyObject.h" @implementation MyObject { MyClassImpl* _impl; } - (int)doSomethingWith:(void *)aParameter { if (!_impl) _impl = [MyClassImpl new]; return [_impl doSomethingWith:aParameter]; } @end
Implement the C Class:
#include "MyObject-C-Interface.h" class MyCPPClass { public: void someMethod(void *objectiveCObject) { int result = MyObjectDoSomethingWith(objectiveCObject, nullptr); } };
This approach provides a more isolated and flexible solution, enabling the Objective-C implementation and the C wrapper to be modified without affecting the C code.
The above is the detailed content of How to Call an Objective-C Method from a C Member Function?. For more information, please follow other related articles on the PHP Chinese website!