Get pointer to underlying data in mex C++ API
4 views (last 30 days)
Show older comments
I would like to get a pointer to the underlying data of an input array, using the C++ mex API, while avoiding copies of the data.
This was partially answered in
eg. I tried
matlab::data::TypedArray<double> ar(std::move(inputs[0]));
double* a = ar.release().get();
and
matlab::data::TypedArray<double> ar(inputs[0]);
double* a = ar.release().get();
However, I've compared that to the result with the C-API,
double *p = mxGetPr(prhs[i]);
and the results are different.
That is, the C++ API must be copying the data. I get that this probably supports safety, but I still want to get at the underlying data, without unnecessary memory copying.
My use case is that I want to call libraries written with xtensor [1], using xt::adapt. I need a pointer to do that.
0 Comments
Answers (1)
Andrew Janke
on 31 Jan 2020
That mxGetPr() call is copying the data. The MEX API changed in R2018a when Matlab switched to the "interleaved complex data model". See https://www.mathworks.com/help/matlab/matlab_external/matlab-support-for-interleaved-complex.html. Now, when you call parts of the MEX API that use the old "separate complex" data model, it does a memory copy to convert the data to the old format. mxGetPr is one of those legacy functions.
Use the new mxGetDoubles() or similar functions instead. https://www.mathworks.com/help/matlab/apiref/mxgetdoubles.html. Those will get you direct access to the new interleaved-complex representation without a copy step.
0 Comments
See Also
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!