Skip to content

Allocating and initializing objects manually

Nat! edited this page Mar 19, 2017 · 1 revision

When you have a block of memory and want it to contain an object. You have to do the following:

id   allocate_instantiate( Class cls, void *memory, size_t size)
{   
   size_t   memory_needed;
   id       obj;

   memory_needed = _mulle_objc_class_get_allocationsize( cls);
   if( memory_needed > size)
       return( nil);
   memset( memory, 0, memory_needed);

   obj = _mulle_objc_objectheader_get_object( memory);
   _mulle_objc_object_set_isa( obj, cls);

   return( obj);
}

Given an object, you can get the memory address back. You must be sure, that the object is not a tagged pointer though:

void   *memory_from_object( id obj)
{
   return( (void *) _mulle_objc_object_get_header( obj));
}