I would to ask how I can access a variable on Fortran from MATLAB without making a copy. Preferrably, I would like to access the variable a variable on Fortran (it may be 'read-only') that was declared and initialized on MATLAB and passed as an input to my Fortran-based MEX function as input (pretty much a pass-by-reference), and if possible, do it for a multidimensional array.
The solutions that I have found so far require copying the variable, which is quite costly for large inputs.
So far, I have tried the approach based on the solution given in the MATLAB documentation, where they implement a function in the form y = times2(x) which doubles my double scalar x. However, it requires copying the variable x, so there is the original x declared on MATLAB and another one on Fortran.
For reference, MATLAB recommends first declaring a pointer and its associated variable
mwPointer x_ptr real*8 x_input
And then copying the content of the MATLAB variable x into the Fortran variable x_input via:
call mxCopyPtrToReal8(x_ptr,x_input,size)
Where size is 1, as x is a scalar, but in my application I will eventually use a multi-dimensional array.
This solution is unappealing when one needs to operate on large arrays, as they would be copied, doubling my memory requirements. I have found this function mexGetVariablePtr which returns a read-only MATLAB pointer that theoretically should give me access to the variable x without copying it.
My question is: how do I access this variable, as the only function that I found in the API documentation, mxCopyPtrToReal, copies the variable.
Additional information:
- I only want to read the contents of the variable 'x' and use as a normal Fortran variable without modifying it.
- The output of 'mexGetVariablePtr' is a 'mwPointer', which seems to not be easy to dereference like regular Fortran pointers.
Thank you for your attention!
I found the solution in a old source.
To those interested, basically you need to declare the appropriate functions as
integer, notmwPointer(which is shown in MATLAB's documentation).The (non-read only) pointer of a is then converted to an integer via:
Lastly, you send the input variable as a dynamic allocated one with
using the operator
%.Finally, you will be able to use the variable in the function
computewithout making a copy. If you change the content of an input variable it will be changed everywhere.The only problem with this approach is that I do not know how to send a multidimensional array without using
reshape, which would require me to make a temporary copy of the variable.For further information, see 1.