[英]Passing string array from Fortran to C/C++ DLL and get array with changed values
I am creating a C/C++ DLL which accepts char*[]
(String array), changes the value in array and return back. 我正在创建一个接受char*[]
(字符串数组),更改数组中的值并返回的C / C ++ DLL。
My C/C++ implementation: 我的C / C ++实现:
int doubleijk_(char* data[]) // what should be the return type ???
{
// code to change array elements
return 0;
}
In Fortran (using ifort) I am calling the DLL's function like this: 在Fortran中(使用ifort),我这样调用DLL的函数:
module variables
type string
character(len=:), allocatable :: str
end type string
end module variables
program Call_CPP
use variables
type(string) :: array(3)
array = [string('xyza'), string('abcd'), string('mnopqrs')]
INTERFACE
! How to write SUBROUTINE for array
SUBROUTINE doubleijk_(arr) BIND(C,NAME='doubleijk_')
!???????WHAT SHOULD BE SUBROUTINE FOR ARRAY OF STRINGS????????
END SUBROUTINE doubleijk_
END INTERFACE
! Body of Call_CPP
call doubleijk_(array)
! print values of array after call
end program Call_CPP
I am able to pass string, integer from Fortran and got changed value from C/C++. 我能够从Fortran传递字符串,整数,并从C / C ++获得更改的值。 What I need is to pass string array from Fortran to C/C++ and get back the array with changed values. 我需要将字符串数组从Fortran传递到C / C ++,并使用更改后的值取回数组。 How do I do this? 我该怎么做呢?
Finally made that working. 终于做到了。 Here is the solution. 这是解决方案。
program Call_CPP
use iso_c_binding, only: c_associated, c_loc, c_ptr
INTERFACE
SUBROUTINE doubleijk_(stringPtrs) BIND(C,NAME='doubleijk_')
use iso_c_binding
TYPE(C_PTR), DIMENSION(3) :: stringPtrs
END SUBROUTINE doubleijk_
END INTERFACE
TYPE(C_PTR), DIMENSION(3) :: stringPtr
CHARACTER(LEN=20), DIMENSION(3), TARGET :: stringArray
DO ns = 1, 3
stringArray(ns) = "My String"//char(0)
stringPtr(ns) = c_loc(stringArray(ns))
END DO
! Body of Call_CPP
call doubleijk_(stringPtr) !Call C function
DO ns = 1, 3
print *, stringArray(ns) !print array after call-changed values
END DO
end program Call_CPP
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.