Passing a String from Matlab to a Fortran Mex Function
조회 수: 1 (최근 30일)
이전 댓글 표시
I am passing a string from a Matlab routine to a Fortran mex function. However, I am not having much luck pulling it out in the Fortran.
% My Simple Matlab Code:
%
temp_string = 'This is a place of business';
Call_String_Test(temp_string);
Could someone please help me to get this string pulled out and printed in the Fortran mex function. I have tried mxgetstring, mxcopyptrtocharacter, mxgetchars, and others. I can't seem to get the write syntax. I either get compiler errors, or matlab blows up. TIA, RICK
댓글 수: 0
채택된 답변
Geoff Hayes
2014년 12월 7일
Hi Rick - the revord.F example does a decent job of describing the steps to read the input string. It can be opened in your editor as
edit([matlabroot '/extern/examples/refbook/revord.F']);
The code that follows is a variation of the this function. Note that I had problems with the call mexErrMsgIdAndTxt ... calls crashing MATLAB, so I just replaced them with a mexPrintf equivalent.
#include "fintrf.h"
C Gateway routine
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
C mexFunction arguments:
mwPointer plhs(*), prhs(*)
integer nlhs, nrhs
C Function declarations:
mwPointer mxCreateString
mwPointer mxGetString
mwPointer mxGetM, mxGetN
integer mxIsChar
C Array information:
mwPointer mrows, ncols
C Arguments for computational routine:
mwSize maxbuf
parameter(maxbuf = 100)
character*120 line
integer*4 k
character*100 input_buf
mwPointer strlen
C Check for proper number of arguments.
if(nrhs .ne. 1) then
write(line,*) 'error: incorrect number of input arguments'
k=mexPrintf(line//achar(13))
return
C The input must be a string.
elseif(mxIsChar(prhs(1)) .ne. 1) then
write(line,*) 'error: input argument is not a string'
k=mexPrintf(line//achar(13))
return
endif
C Get the size of the input string.
mrows = mxGetM(prhs(1))
ncols = mxGetN(prhs(1))
C Get the length of the input string and validate.
strlen = mrows*ncols
if (strlen .gt. maxbuf) then
write(line,*) 'error: input is greater than max str size'
k=mexPrintf(line//achar(13))
return
endif
C Get the string.
status = mxGetString(prhs(1), input_buf, maxbuf)
write(line,*) 'str = ', input_buf
k=mexPrintf(line//achar(13))
return
end
The code checks to make sure that there is only one string input. Note how the input string can only have a fixed number of characters. I saved the above to a file called readString.F and compiled as mex readString.F. In the Command Window, I called this function as
>> readString(1)
error: input argument is not a string
>> readString('hello',2)
error: incorrect number of input arguments
>> readString('hello')
str = hello
>> readString('This is a place of business')
str = This is a place of business
See the attached for a working copy of this code.
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!