passing a structure into a fortran subroutine in a mex file.

6 views (last 30 days)
Hi, I am trying to pass a matlab structure into a fortran subroutine using mex files. I am not sure how to do that since I need to convert the matlab structure into a fortran data type. I was wondering if anyone can help with showing a simple example of passing a matlab structure into a fortran subroutine.
Thanks

Answers (1)

James Tursa
James Tursa on 10 May 2015
Edited: James Tursa on 10 May 2015
You will have to copy the data one field at a time. This is true for both passing in a structure and passing out a structure, primarily because of the fact that the MATLAB data is not contiguous in memory whereas the Fortran data most likely will need to be contiguous. I don't have a Fortran compiler handy to test any of the following, but the process would look something like this for known field sizes (CAUTION, this is a bare bones outline with no argument checking and untested):
MATLAB m-code:
myStruct.scalar = 5;
myStruct.vector = [1 2 3];
myStruct.matrix = [1 2;3 4];
myMexRoutine(myStruct);
Fortran code for myMexRoutine:
#include "fintrf.h"
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
implicit none
integer nlhs, nrhs
mwPointer plhs(*), prhs(*)
!-FUN
mwPointer, external :: mxGetField
real*8, external :: mxGetPr
!-LOC
TYPE FortranStruct
REAL*8 scalar
REAL*8 vector(3)
REAL*8 matrix(2,2)
end type FortranStruct
TYPE(FortranStruct) myStruct
mwPointer field
mwPointer pr
mwSize n
mwIndex :: i = 0
!-----
field = mxGetField(prhs(1),i,"scalar")
pr = mxGetPr(field)
n = 1
call mxCopyPtrToReal8(pr, myStruct%scalar, n)
field = mxGetField(prhs(1),i,"vector")
pr = mxGetPr(field)
n = 3
call mxCopyPtrToReal8(pr, myStruct%vector, n)
field = mxGetField(prhs(1),i,"matrix")
pr = mxGetPr(field)
n = 4
call mxCopyPtrToReal8(pr, myStruct%matrix, n)
And if you wanted to pass out a structure you would need to do data copies in the reverse direction.
  3 Comments
James Tursa
James Tursa on 29 Mar 2023
Edited: James Tursa on 29 Mar 2023
@Michael Loibl Please post a new Question, with a small example of what you have on the Fortran side and what you want on the MATLAB side.
Michael Loibl
Michael Loibl on 30 Mar 2023
I actually found an answer for myself in the meantime. But thank you for the reply.

Sign in to comment.

Categories

Find more on Fortran with MATLAB 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!