如何分配FORTRAN例程QUOT里的数组,称为QUOT;从C [英] How to allocate an array inside fortran routine "called" from C
问题描述
我觉得标题说我需要什么。我知道我们可以用ASD功能来做到这一点,但由于某些原因,我需要做的Fortran语言分配(即子程序asd_)。这里是C code:
I think title says what I need. I know we can use "asd" function to do this, but for some reasons I need to do the allocation in Fortran (i.e. in subroutine "asd_"). Here is the C code:
#include <stdio.h>
void asd(float **c) {
*c = (float *) malloc (2*sizeof(float));
**c =123;
*(*c+1)=1234;
}
void asd_(float **c);
main () {
float *c;
asd_(&c);
// asd(&c); would do the job perfectly
printf("%f %f \n",c[0],c[1]);
return 0;
}
这里是Fortran的code:
And here is the Fortran code:
subroutine asd(c)
implicit none
real, pointer, allocatable ::c(:)
print *, associated(c)
if(.not. associated(c)) allocate(c(2))
end subroutine
这给出了随机分段错误。任何帮助将是AP preciated。
This randomly gives segmentation fault. Any help would be appreciated.
推荐答案
下面是另一种解决办法,如果你想使用Fortran内的类型。这是我的情况,因为我需要从外部库调用例程,使用pre指定的数据类型。这基本上是一个包装的Fortran子程序完成。这里是C code:
Here is also another solution, if you want to use Fortran intrinsic types. This was my case, since I needed to call routines from an external library, using the pre-specified data types. This is basically done with a wrapper Fortran subroutine. Here is the C code:
void mywrap_(void **);
void myprint_(void *);
main () {
void *d;
mywrap_(&d);
myprint_(d);
return 0;
}
这里是包装:
subroutine mywrap(b)
implicit none
include "h.h"
type(st), target, save :: a
integer, pointer :: b
interface
subroutine alloc(a)
include "h.h"
type(st) a
end subroutine alloc
end interface
call alloc(a)
b => a%i
end
和Fortran语言的codeS:
And the Fortran codes:
subroutine alloc(a)
implicit none
include "h.h"
type(st) a
a%i = 2
a%r = 1.5
if (allocated(a%s)) deallocate(a%s)
allocate(a%s(2))
a%s(1) = 1.23
a%s(2) = 1234
end
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
subroutine myprint(a)
implicit none
include "h.h"
type(st) a
print *,"INT: ", a%i
print *,"REAL: ", a%r
print *,"ALLOC: ", a%s
end
和头文件h.h
type st
sequence
integer i
real r
real, allocatable :: s(:)
end type
请注意,这样一来所有的对象都是在C不透明的。
Note, this way all the objects are opaque in the C.
这篇关于如何分配FORTRAN例程QUOT里的数组,称为QUOT;从C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!