How do I pass a string from Visual Basic 2010 to a Fortran DLL?
I can pass integers, singles, doubles, and arrays of all these back and forth with no problem. But I can't figure out how to pass a string in Visual Basic 2010 to a character variable in the Fortran DLL. I keep getting the PInvokeStackImbalance
error. I could just convert the Visual Basic string to an integer array containing the ASCII code for each character, send that, and convert back inside the DLL, but that's pathetic. There must be a simple way to do this.
I 开发者_如何学Pythonfirst tried using Dim txt(50) as Char
in VB2010, and character*50 txt
in the DVF F90 DLL but that didn't work.
Then I tried Dim txt as String
in Visual Basic 2010 and made the string 50 characters long (also tried 49) but this didn't work.
I'm hoping that somebody else out there wants to pass filenames and such to their DLL.
Well I did it with C# and it was simple:
FORTRAN CODE (Compaq Visual Fortran)
SUBROUTINE TEST_STR(A, N)
!DEC$ ATTRIBUTES DLLEXPORT :: TEST_STR
!DEC$ ATTRIBUTES ALIAS:'TEST_STR' :: TEST_STR
!DEC$ ATTRIBUTES VALUE :: N
INTEGER*4, INTENT(IN) :: N
CHARACTER(LEN=N) :: A
PRINT '(1X,A)', "STRING RECEIVED:"
PRINT '(1X,A8, A50)', "VALUE=", A
END SUBROUTINE
.NET Code (C# 2008)
[DllImport("mathlib.dll")]
static extern void TEST_STR(string A, int n);
...
string S = new string('@', 50);
TEST_STR(S, S.Length);
But I cannot make any changes and return the string (yet). Maybe this is sufficient to get you going.
Have you tried specifying <MarshalAs(UnmanagedType.LPStr)>
in the P/Invoke?
Public Declare Auto Sub YOUR_SUB Lib "YOUR_DLL.Dll" (<MarshalAs(UnmanagedType.LPStr)> YOUR_VARIABLE As String)
More on that here:
http://msdn.microsoft.com/en-us/library/s9ts558h%28VS.71%29.aspx
and
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute%28VS.80%29.aspx
精彩评论