How to create NSAutoreleasePool without Objective-C?

I have a multi-platform game written in C ++. In the Mac version, although I don’t have any obj-c code, one of the libraries I use seems to be an automatic release and I get memory leaks for this since I did not create NSAutoreleasePool.

I want to be able to create (and destroy) NSAutoreleasePool without using obj-c code, so I don’t need to create a .m file and modify build scripts just for that. Is it possible? How can I do that?

OBS: tagged C and C ++, because the solution will be executed in any of these languages.

+7
source share
1 answer

You cannot avoid creating an instance of Objective-C at runtime, but apparently you already have one of them.

If you want to interact with the C runtime, you can use the Objective-C API as described in the Objective-C Runtime Programming Guide and Objective-C Runtime Reference .

The idea is something like this (untested):

#include <objc/runtime.h> #include <objc/objc-runtime.h> id allocAndInitAutoreleasePool() { Class NSAutoreleasePoolClass = objc_getClass("NSAutoreleasePool"); id pool = class_createInstance(NSAutoreleasePoolClass, 0); return objc_msgSend(pool, "init"); } void drainAutoreleasePool(id pool) { (void)objc_msgSend(pool, "drain"); } 

If you want to call these functions from another file, you will of course need to include objc / runtime.h. Or, alternatively, you can use id for void * in return from allocAndInit function and accept void * and drop back to id in drain function. (You can also format-declare struct objc_object and typedef struct objc_object * id, but I believe that this is not a guaranteed correct definition.)

You do not need to pass the -lobjc command to your link.

Needless to say, it probably works less, just to have your build scripts process .m files.

+2
source

All Articles