MATLAB Answers

How to transfer parameter between C and fortran

2 ビュー (過去 30 日間)
Rylan 2019 年 11 月 12 日
コメント済み: Rylan 2019 年 11 月 13 日
Hello, everyone! Recently, I'm trying to add some source files in c and fortran into my program. And parameters is transfered from matlab to C, then from C to Fortran. After some manipulation, the result will flow from Fortran to C, then to matlab. Before doing this, I did a simple test just to show whther it works, the following is my sourece code in C(.c)
#include "mex.h"
#include <stdio.h>
extern void __stdcall SUB(int *a, int *b);
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
int nlev = 6;//Layer of the three model
int data = 7;
SUB( &nlev, &data );
And the following is the source code in fortran(.F90)
subroutine sub(a, b)
implicit none
integer :: a,b
write(124,*) 'The memory allocation part'
write(124,*) a
write(124,*) b
write(124,*) 'The memory allocation finish'
end subroutine
If everything goes well, the output would be a file named 'Dataoutput.txt' with the following result:
The memory allocation part
The memory allocation finish
But the result is not as expected, and the result is as follows:
The memory allocation part
The memory allocation finish
What's the problem here, can anybody tell me?
Thx a lot!

  0 件のコメント



James Tursa
James Tursa 2019 年 11 月 12 日
編集済み: James Tursa 2019 年 11 月 12 日
Maybe the Fortran compiler settings are compiling the default integer as 8-byte integers. Try forcing the Fortran to use 4-byte integers, since that is almost certainly what the C int is. E.g.,
integer*4 :: a,b
On the C side, although not required, suppose the C compiler happened to put the 4-byte integers nlev and data next to each other in memory. Then suppose that the Fortran used the address of the first one as the address of a 64-bit integer. The expected result would be this:
>> typecast(int32([6 7]),'int64')
ans =
And that is in fact what you see above for the first output number. The other Fortran number is using the 7 and some garbage to get the second output (could have crashed actually since you are accessing invalid memory). This confirms that the Fortran side is assuming 8-byte integers for the default integer type, causing a type mismatch in the arguments.

  1 件のコメント

Rylan 2019 年 11 月 13 日
Thanks for your answer, I have confirmed this. Thanks again!


その他の回答 (0 件)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by