How to exchange data between two C++ MEX files
Show older comments
Good morning,
I need to write a two (or more) C++ mex functions
- the first MEX function allocates dynamically a std::vector<double> and fills it with some data,
- the second MEX function makes some other computations on the same vector allocated by the first MEX function.
Indeed I managed to do it in the following way:
- the first MEX function invokes mexLock so as to prevent the memory to be released after execution, allocates the vector, and returns to Matlab its address into a uint64 integer ptr_vec:
std::vector<double> *p_data = new std::vector<double>;
std::vector<double> &data = *p_data;
// Fill the vector with some data
ptr_vec = reinterpret_cast<uint64_t>(p_data); // ptr_vec is returned to MATLAB
- The second MEX function accepts this pointer ptr_vec, and does some job:
std::vector<double> &data = *reinterpret_cast<std::vector<double> *>(ptr_vec);
Left aside the burden of avoiding memory leaks and the danger of using "naked" (= not smart) pointers, on my PC the programs work fine (Matlab R2021b on Linux Fedora 34). However, my questions are:
- Is this the right way to preceed? Is this kind of technique reliable and portable over other architectures / MATLAB versions?
- It is mandatory to invoke mexLock in the first MEX function?
Thanks
R.S.
Accepted Answer
More Answers (0)
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!