Is it possible to do an in-place mxCalloc at a specific address, like "placement new"?

1 view (last 30 days)
In my mex function I use memory mapped files with boost. It allocates a region in memory for me, and then I construct my data structure in that memory with placement new: MapData *md = new (addr) MapData;
I need to pass that data to a mxArray using mxSetData. But matlab crashes when I do that, presumably because the dynamic memory was allocated internally by boost, and not using mxCalloc.
Is there a way to fix that?
I know I can instead manually copy the data to the mxArray using the mxGetData function, but I would rather avoid the unnecessary copying.

Answers (1)

James Tursa
James Tursa on 27 Nov 2017
You cannot attach memory allocated from native C/C++ functions to an mxArray. Period. It will result in an assert seg fault. If you have to allocate the memory using native C/C++ functions, then you will be forced to do a data copy to get the data into an mxArray. That's just the way it is.
An alternative, which may not be an option for you, is to mxCalloc or mxMalloc the memory for your MapData object. E.g., something like
MapData *md = (MapData *) mxMalloc(sizeof(MapData));
You could then legally mxSetData that address into an mxArray without getting an assert seg fault.

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!