【发布时间】:2021-11-17 03:46:40
【问题描述】:
代码是 Fortran 主程序调用 C 函数并返回整数数组指针的示例。问题是我想将 Fortran 指针分配给具有 C 数组值的 Fortran 数组,所以我让 Fortran 指针同时指向两个目标。我现在知道这是错的。但是由于 Fortran 没有像 *p 这样的操作,我怎样才能使 Fortran 数组与分配的 Fortran 指针具有相同的值?
fortran 主要代码在这里:
program Test
use, intrinsic :: iso_c_binding, only : c_ptr, &
c_f_pointer, &
c_int
USE FTN_C
type(c_ptr) :: c_p
integer(c_int), pointer :: f_p(:)
integer, target :: Solution(10)
c_p = C_LIBRARY_FUNCTION()
call c_f_pointer(c_p, f_p, [10])
!c_f_pointer assigns the target, cptr, to the Fortran pointer,
fptr, and specifies its shape.
f_p => Solution ! Solution cannot be pointed
print *, f_p
print *, Solution
end program Test
C代码在这里:
int* C_Library_Function(){
static int r[10];
for (int i = 0; i < 10; ++i){
r[i] = i;
}
return r;
}
结果显示:
./a.out
0 1 2 3 4 5 6 7 8 9
337928192 1 338811792 1 1073741824 0 337933009 1 338567264 1
仅供参考,ISO_C_Binding 模块代码是
MODULE C_Binding
USE, INTRINSIC :: ISO_C_BINDING
END MODULE C_Binding
module FTN_C
INTERFACE
FUNCTION C_LIBRARY_FUNCTION() BIND(C,&
NAME='C_Library_Function')
USE C_Binding
IMPLICIT NONE
type(C_PTR) :: C_LIBRARY_FUNCTION
END FUNCTION C_LIBRARY_FUNCTION
END INTERFACE
end module FTN_C
【问题讨论】:
-
欢迎您,我建议使用tour。
标签: pointers fortran fortran-iso-c-binding