André
André

Reputation: 75

Custom memory allocator for OpenCV

Is it possible to set a custom allocator for OpenCV 2.3.1? I have a memory pool created and I want OpenCV to use that pool for what it needs.

Is that possible? If it is, how can it be done?

Updated:

I made some developments since last answer, but I still have some problems. This is the code I have now:

CvAllocFunc allocCV() 
{ 
     return (CvAllocFunc) MEMPOOL->POOLalloc(sz); 
}

CvFreeFunc deallocCV()
{
    return (CvFreeFunc) MEMPOOL->POOLfree(ptr);
}

...

cvSetMemoryManager(allocCV(),deallocCV(),data);

Now, my question is, how can I have access to the size and the pointer to the data I want to allocate and later to deallocate?

Just found out: The version of OpenCV I'm using (2.3.1) throws an error when using cvSetMemoryManager. The reason is in its source code:

void cvSetMemoryManager( CvAllocFunc, CvFreeFunc, void * )
{
    CV_Error( -1, "Custom memory allocator is not supported" );
}

I was very disappointed with this. I guess I can't use a custom memory pool with OpenCV anymore!

Upvotes: 4

Views: 3053

Answers (1)

Viktor Latypov
Viktor Latypov

Reputation: 14467

Right from the docs

http://opencv.willowgarage.com/documentation/c/core_utility_and_system_functions_and_macros.html#setmemorymanager

Use the

void cvSetMemoryManager(CvAllocFunc allocFunc=NULL, CvFreeFunc freeFunc=NULL, void* userdata=NULL)

function.

Your code

cvSetMemoryManager(allocCV(),deallocCV(),data);

is WRONG.

See what happens: you call allocCV and deallocCV functions (they return some pointer which is quietly converted to cvAllocFunc) !

And this is only the beginning. See the docs for alloc/dealloc semantics. You should write allocCV/deallocCV with correct signatures.

void* CV_CDECL allocCV(size_t size, void* userdata)
{
     return ((YourMemPoolTypeWhichIDoNotKnow*)userdata)->POOLalloc(size);
}

int CV_CDECL deallocCV(void* pptr, void* userdata)
{
    return ((YourMemPoolTypeWhichIDoNotKnow*)userdata)->POOLfree(pptr);
}

and then pass your MEMPOOL in the 'userdata' parameter:

cvSetMemoryManager(&allocCV, &deallocCV, (void*)MEMPOOL);

This is a standard way for a library to provide user callbacks.

Upvotes: 1

Related Questions