如何在“调用"的 fortran 例程中分配数组?从 C [英] How to allocate an array inside fortran routine "called" from C
问题描述
我认为标题说明了我的需要.我知道我们可以使用asd"函数来执行此操作,但由于某些原因,我需要在 Fortran 中进行分配(即在子程序asd_"中).这是C代码:
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
",c[0],c[1]);
return 0;
}
这是 Fortran 代码:
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
这会随机给出分段错误.任何帮助将不胜感激.
This randomly gives segmentation fault. Any help would be appreciated.
推荐答案
如果你想使用 Fortran 内部类型,这里还有另一个解决方案.这是我的情况,因为我需要使用预先指定的数据类型从外部库调用例程.这基本上是通过包装 Fortran 子例程完成的.这是C代码:
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 代码:
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 例程中分配数组?从 C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!