I am writing a mex-file (using C++) that will accept a memory address as an input, and operate on data at that memory address. Because I am forced to use MATLAB as my environment, my program can only accept MATLAB data types as inputs (char, bool, float, double, and int). How can I go about assigning my input value to a pointer?
Pseudocode:
// Outside of program
// double input_arg = hex2dec('00C2E4E8')
double *pointer;
pointer = (double *)input_arg;
// pointer == hex2dec('00C2E4E8')
Basically, this can be seen as me hardcoding the value of a pointer similar to:
double *pointer = (double *)hex2dec('00C2E4E8');
I am receiving the error:
error C2440: ‘=’ : cannot convert from ‘double’ to ‘double *’
I have also tried using static/const/reinterpret/dynamic_cast, but I don’t really understand how they work (and I couldn’t get them to work). Is it possible at all to manually assign memory address values to pointers?
What you’re trying to do is dangerous because you’re passing raw pointers to some C++ code, making assumptions about what exists at that location and executing code based on those assumptions. But let’s say you’ve taken care of all those security issues.
You probably want to pass the pointer to your MEX file as a UINT64 (so that the code can be recompiled and used as is on a 64-bit installation of MATLAB).
On the MATLAB side:
Within your mex function:
Note: You can do the same with a double as well, just change the
mxGetClassIDcheck to look formxDOUBLE_CLASS. In this case the cast expression becomes:EDIT:
What I’ve said about being about to get this code to work on a 32 or 64-bit machine is only true if both machines are little endian. Otherwise, if you pass a 32-bit pointer in a 64-bit uint on a big-endian machine and cast it to a
double *you’ll get a pointer that is0x00000000.You can handle the endianness issues by using the MATLAB function
computerto detect machine endianness. If byte swapping is needed you can useswapbytes. To execute these functions from your C++ code usemexCallMATLABWithTrap.