Reputation: 2147
I'm creating a cross platform library using C. I have a piece of code like the following, in which I'm using the libc memory management functions directly:
myObject* myObjectCreate(void)
{
...
myObject *pObject = (myObject*)malloc(sizeof(*pObject));
...
}
void myObjectDestroy(myObject *pObject)
{
...
free(pObject);
...
}
I understand these memory management functions are not always available, especially on embedded systems based on low-end microcontrollers. Unfortunately my library needs to be compilable on these systems.
To work around this problem, I suppose I'd have to make these functions customisable by my library client.
So, what are the recommended ways to achieve this?
Upvotes: 1
Views: 196
Reputation: 62106
Use function pointers.
Define the following pointers in the library:
void* (*CustomMalloc)(size_t) = NULL;
void (*CustomFree)(void*) = NULL;
And prior to using of the library functions initialize these pointers to point to custom implementations of malloc()
and free()
. Or initialize them to point to the real malloc()
and free()
.
Inside of the library replace malloc(size)
with CustomMalloc(size)
and free(pointer)
with CustomFree(pointer)
.
Upvotes: 1
Reputation: 13446
Use conditional compile, i.e. define some macro's like LIBC_AVAIL
, LIBC_NOT_AVAIL
and include different code when compiling.
Upvotes: 0
Reputation:
There are many approaches.
I use #if, combined with compiler provided defines, to have per platform behaviour.
Should a given functionality (such as malloc) be found, #define MYLIB_MALLOC can be defined.
Then, later, you can check for #ifdef MYLIB_MALLOC and if not present, provide a dummy malloc function, which will allow your code to compile.
Upvotes: 2