passing a structure into a fortran subroutine in a mex file.
조회 수: 6 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (1개)
James Tursa
2015년 5월 10일
편집: James Tursa
2015년 5월 10일
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
James Tursa
2023년 3월 29일
편집: James Tursa
2023년 3월 29일
@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
2023년 3월 30일
I actually found an answer for myself in the meantime. But thank you for the reply.
참고 항목
카테고리
Help Center 및 File Exchange에서 Fortran with MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!