将结构化数据类型从Fortran传递到C ++ [英] Passing a structured data type from Fortran to C++
问题描述
我为一些Fortran开发C ++ API常规。我需要结构的内容在调用Fortran例程之间持久化。
我正在考虑使用loc获取结构的地址,并将地址传递给C ++
当从C ++再次调用Fortran例程并将地址传回给Fortran时,以某种方式将它转换为原始结构,然后将其用于计算。 p>
我可以用什么方法来完成这项工作?
谢谢。
编辑:我的代码基于评论/建议。
当调用C_LOC时程序崩溃(如果我将对C_LOC的调用注释掉,那么程序不会崩溃)。
子程序TEST(a,b,c,d,e,mystruct,ier)BIND(C,NAME ='TEST')
使用mymodule
USE,INTRINSIC :: ISO_C_BINDING
implicit none
TYPE(C_PTR):: mystruct
TYPE(mymodule),TARGET :: origstruct
INTEGER :: a,b,c
DOUBLE PRECISION :: d (*),e(*)
INTEGER :: ier
!用origstruct和其他参数做某事
print *,'here 1'
mystruct = C_LOC(origstruct)
print *,'here 2'
end
<在Fortran 2003(现在大多数编译器支持)下,您可以使用标准的ISO_C_BINDING模块。如果你对获得的C指针是不透明的(也就是你只是想要一个 void *
)感到满意,你可以使用 C_LOC
函数:
use,intrinsic :: ISO_C_BINDING
类型(your_struct_t),target :: your_obj
type(C_PTR):: p
p = C_LOC(your_obj)
$ b $然后你可以将这个指针传递给一些C程序:
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $子程序mycproc(x,n ,userdata)bind(C)
use,intrinsic :: iso_c_binding
integer(c_int),intent(in),value :: n
real(c_double),intent(in):: x(n)
type(c_ptr),intent(in),value :: userdata
结束子程序
结束界面
调用mycproc(x,size(x ),p)
I have a structured type in Fortran that contains lots of data including pointers (real*8 pointer data type).
I am developing a C++ API for some Fortran routine. I need the contents of the structure to persist between calls to the Fortran routine.
I was thinking about getting the address of the structure using loc and pass the address to the C++ side.
When Fortran routine is called again from C++ and the address is passed back to Fortran, somehow typecast it to the original structure and then use it for computation.
What approach can I use to accomplish this?
Thanks.
EDIT: my code based on the comments/suggestions. The program crashes when C_LOC is called (if I comment out the call to C_LOC then the program does not crash).
subroutine TEST(a,b,c,d,e,mystruct,ier) BIND(C, NAME='TEST')
use mymodule
USE, INTRINSIC :: ISO_C_BINDING
implicit none
TYPE(C_PTR) :: mystruct
TYPE(mymodule), TARGET :: origstruct
INTEGER :: a, b, c
DOUBLE PRECISION :: d(*), e(*)
INTEGER :: ier
!Do something with origstruct and other arguments
print *, 'here 1'
mystruct= C_LOC(origstruct)
print *, 'here 2'
end
Under Fortran 2003 (supported by most compilers nowadays), you can use the standard ISO_C_BINDING module. If you are happy with the obtained C pointer being "opaque" (that is, you just want a void*
), you can use the C_LOC
function:
use, intrinsic :: ISO_C_BINDING
type(your_struct_t), target :: your_obj
type(C_PTR) :: p
p = C_LOC(your_obj)
You can then pass this pointer to some C procedure:
interface
subroutine mycproc(x, n, userdata) bind(C)
use, intrinsic :: iso_c_binding
integer(c_int), intent(in), value :: n
real(c_double), intent(in) :: x(n)
type(c_ptr), intent(in), value :: userdata
end subroutine
end interface
call mycproc(x, size(x), p)
这篇关于将结构化数据类型从Fortran传递到C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!