为什么这种将指针从C ++传递到Fortran的尝试不起作用? [英] Why is this attempt to pass a pointer from C++ to Fortran not working?
问题描述
我需要将动态数组从c ++传递给Fortran.我做了很多研究,以整理出我认为应该起作用的示例,但事实并非如此.该程序应在c ++程序中创建一个数组,将该数组的指针传递给Fortran例程,将C指针转换为Fortran指针,然后在Fortran端打印该数组.
I need to pass a dynamic array from c++ to Fortran. I did a lot of research to put together an example that I thought should work, but it doesn't. The program should create an array in the c++ program, pass the pointer of that array to the Fortran routine, convert the C pointer to a Fortran pointer, and then print the array on the Fortran side.
我的c ++主程序:
using namespace std;
extern "C" {
void cinterface(int*,int*);
}
int main()
{
int carray[]={0,1,2,3,4};
int carray_siz=5;
cinterface(&carray_siz,carray);
return 0;
}
我的Fortran例程:
My Fortran routine:
module fortmod
use ISO_C_BINDING
implicit none
contains
subroutine cinterface(carray_siz,carray_ptr) bind(C)
implicit none
integer(c_int), intent(in) :: carray_siz
type(c_ptr), intent(in) :: carray_ptr
integer(c_int), pointer :: pfarray(:) => NULL()
call C_F_POINTER(carray_ptr,pfarray,[carray_siz])
print *, pfarray
end subroutine cinterface
end module fortmod
我将其构建为:
gfortran -c fortmod.f90
g++ main.cpp fortmod.o -lgfortran
但是当我运行它时,它不是打印数组值,而是说:
But when I run it, instead of printing the array values, it says:
Segmentation fault (core dumped)
我对指针的概念是陌生的,所以我认为我不了解指针如何正常工作.您能否指出运行此程序时为什么出现此内存错误?
I'm new to the idea of pointers, so I'm thinking I'm not understanding how they work correctly. Can you please point out why I'm getting this memory error when I run this?
推荐答案
摘自gfortran手册:
From the gfortran manual:
如果指针是可互操作过程的伪参数,则通常必须为 使用VALUE属性声明. void *匹配TYPE(C_PTR),VALUE,而TYPE(C_PTR)单独匹配void **.
If a pointer is a dummy-argument of an interoperable procedure, it usually has to be declared using the VALUE attribute. void* matches TYPE(C_PTR), VALUE, while TYPE(C_PTR) alone matches void**.
我的Fortran例程正在寻找指针的地址,而不是指针指向的地址.因此,如果我对此修改c ++方面:
My Fortran routine was looking for the address of the pointer, not the address to which the pointer is pointing. So if I modify the c++ side to this:
使用命名空间标准;
extern "C" {
void cinterface(int*,int**);
}
int main()
{
int carray[]={0,1,2,3,4};
int carray_siz=5;
cinterface(&carray_siz,&carray);
return 0;
}
重新构建并重新运行,我现在得到:
re-build and re-run, I now get:
0 1 2 3 4
符合预期.
这篇关于为什么这种将指针从C ++传递到Fortran的尝试不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!