Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29618 Discussions

Exchange string array between C# and fortran DLL

Arash_Rasekh
Beginner
2,266 Views

Hi,

I need a simple way to return an array of strings with unknown size to C#. Here there is a sample code of fortran subroutine:

[fortran]

subroutine testStringArray(strArr)
! directive
!DEC$ ATTRIBUTES DLLEXPORT, Alias:'testStringArray' :: testStringArray
! argument
character(len=32),allocatable,intent(out) :: strArr(:)
! local variable
integer :: size
! main
print*, 'Please enter the size of array:'
read(*,*) size
allocate(strArr(size))
strArr='Hello world'C
end subroutine testStringArray

[/fortran]

Can anyone give me a C# code to invoke this subroutine?

There is no matter in changing the directives, interface, arguments and body of subroutine. my main goal is returing strings to C#.

Best regards, Arash.

0 Kudos
4 Replies
Steven_L_Intel1
Employee
2,266 Views

You can't use allocatable or deferred-shape arrays with non-Fortran languages - at least not today. (The Fortran standard has proposed further enhancements of C interoperability that would allow this in the future.)  If you make strArr a scalar of type C_PTR (from ISO_C_BINDING), create a local allocatable of the declaration you have now, then use C_LOC to assign to strArr the address of the local, it would return to the caller a pointer to the data. You'll need to separately return the size. Taking that data pointer and converting it to something usable in C# is an exercise left for the reader.

0 Kudos
Arash_Rasekh
Beginner
2,266 Views

Thank you Steve for your answer. I was looking for a way to return array by argument in order to reduce the chance of occurrence of unexpected situations. But it seem there is no way and I have to use memory address and pointer.

Best regards, Arash.

0 Kudos
Steven_L_Intel1
Employee
2,266 Views

I almost forgot - if you do this with ALLOCATABLE, you also need to make the variable SAVE. Or you can use POINTER.

0 Kudos
Anthony_Richards
New Contributor I
2,266 Views

Also, see my note re: using SafeArray on your other thread.

0 Kudos
Reply