MATLAB: Usage of calllib, libpointer, and libstruct with DLL that returns memory

callliblibpointerlibstructloadlibraryunloadlibrary

Dear Folks,
I have three design goals based on speed, thread safety, and Application developer protection. The proposed solution is to have the Application hold all the memory required by the Algorithm that it calls inside an Application for loop. So the Algorithm has API functions that return I/O memory structures that the Application will hold onto (and pass to the Algorithm in each successive call). When the Application is done, it calls Deallocate API functions to release that memory. We would like all Applications to use the API in the same way, if possible. This includes our Matlab testing platform.
Is it possible to use calllib() and libpointer() in a Matlab function if the DLL is returning memory for Matlab to attach to the libpointer object? The DLL has "Allocate" and "Deallocate" functions that handle memory management for the I/O to the main DLL API interface function. It seems that I can use calllib() and libpointer() to pass data back-n-forth, but when I go to release the memory, I get these conditions:
1. If I release the memory by calling Deallocate() functions and passing the libpointer object and then followup with a "clear" or "unloadlibrary()", Matlab crashes.
2. If I release the memory by not using the DLL's Deallocate functions, but instead just rely on Matlab's "clear", then I get a memory leak that quickly builds up one iteration after another.
Can anyone explain to me if there is a workaround to this besides making an intermediate wrapper Application? Note that we are returning memory via return statements, rather than through the argument list.
Best regards, Kris

Best Answer

You should be able to do what you are trying to do but have a bug or design flaw.
It is best to keep all memory in a single structure owned by the same owner. This line: t.Value.waves = libpointer('doublePtr',matlabstruct.waves); places a MATLAB owned and managed memory object inside t that is owned and allocated by your DLL. You free t then clear it in MATLAB but MATLAB does not know it is deallocated and goes to free waves causing a crash.
Without seeing the definition of the structure (in c) you are returning and a bit more info on what is expected I may not be able to give a complete response but you could start by trying this sequence however I have doubts that you want to make the above pointer assignment to waves.
%correct order to free t given its construction that I have some doubts about.
t.Value.waves=[]; or = libpointer;
t.Value.range=[];
calllib('DLL32', 'DeallocateInput', t);
clear t;