I want to allocate an NSObject onto its own virtual memory page. Is this possible? It seems trivial if we could still use NSZones, but they are deprecated. I tried using NSZoneFromPointer, but it always returned nil. According to Tips for Allocating Memory:
For large memory allocations, where large is anything more than a few virtual memory pages, malloc automatically uses the vm_allocate routine to obtain the requested memory.
Thus, it seems like I should be able to just make my object as large as a few pages thusly:
@interface MyObject : NSObject {
int[40960]; // 4096 is the default page size, so this is 10 pages.
}
@implementation MyObject
@end
I realize this is a hack, but would it work consistently? Is there a better way?
From twitter:
objc_constructInstance(…) might let you do what you want...
From <objc/runtime.h>:
/**
* Creates an instance of a class at the specific location provided.
*
* @param cls The class that you wish to allocate an instance of.
* @param bytes The location at which to allocate an instance of \e cls.
* Must point to at least \c class_getInstanceSize(cls) bytes of well-aligned,
* zero-filled memory.
*
* @return \e bytes on success, \c nil otherwise. (For example, \e cls or \e bytes
* might be \c nil)
*
* @see class_createInstance
*/
OBJC_EXPORT id objc_constructInstance(Class cls, void *bytes)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0)
OBJC_ARC_UNAVAILABLE;
It looks like objc_constructInstance is the answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With