简体   繁体   English

从Fortran访问C ++结构数组?

[英]Access array of C++ structs from Fortran?

In C++, I allocate an array of S. In Fortran, I want to access elements of this array. 在C ++中,我分配了一个S数组。在Fortran中,我想访问这个数组的元素。 How can I do this? 我怎样才能做到这一点?

C++: C ++:

struct S {double a; double b;};
S *arrayOfS;
arrayOfS = (S *)new S[123]; // allocate

Fortran 2003: Fortran 2003:

USE ISO_C_Binding
TYPE, BIND(C) :: SFortran
REAL(c_double) :: a,b
END TYPE SFortran

S and SFortran should now be interoperable, but I also need to have a way to access the elements of the array declared in C++. S和SFortran现在应该是可互操作的,但我还需要有一种方法来访问在C ++中声明的数组元素。 I'd like to have SC(5)%a in Fortran correspond to arrayOfS[4].a in C++. 我希望Fortran中的SC(5)%a对应于C ++中的arrayOfS [4] .a。 How do I declare and set the proper value for Fortran array SC that will have this access? 如何为具有此访问权限的Fortran阵列SC声明和设置正确的值?

You could: 你可以:

1) pass the C++ array to a Fortran BIND(C) procedure that takes an appropriate array argument. 1)将C ++数组传递给Fortran BIND(C)过程,该过程采用适当的数组参数。

SUBROUTINE proc(array) BIND(C, NAME='proc')
  ...
  TYPE(SFortran) :: array(*)

WIth this approach you might also want to pass the size of the array across and make the array argument explicit shape. 使用这种方法,您可能还希望传递数组的大小并使数组参数显式化。

b) have the array pointer as an extern "C" global on the C++ side, and then interoperate through a Fortran module variable with BIND(C). b)将数组指针作为C ++端的外部“C”全局,然后通过Fortran模块变量与BIND(C)进行互操作。

MODULE some_module
  USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_PTR, C_F_POINTER
  ...
  TYPE(C_PTR), BIND(C, NAME='arrayOfS') :: array_ptr
  ...
  ! In a procedure in the module...
  TYPE(SFortran), POINTER :: array(:)
  CALL C_F_POINTER(array_ptr, array, [123])

Again it might suit to have size of the array available separately to avoid hard coding it in the C_F_POINTER reference. 同样,它可能适合单独提供阵列的大小,以避免在C_F_POINTER引用中对其进行硬编码。

Which approach is best depends on your requirements! 哪种方法最好取决于您的要求!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM