[Mono-dev] Dllimporting Fortran API in C#

Jonathan Pryor jonpryor at vt.edu
Fri Jul 14 05:13:18 EDT 2006


This message really belongs on mono-list, but I'll answer it here...

On Fri, 2006-07-14 at 11:51 +0530, Sunil Venkateswara wrote:
> I am exporting a function in fortran...[and] to import the same
> fortran code by DLLIMPORT, using the following code ( added a write
> call and removed module definition)
> !----------
> ! FORTRAN EXPORT
> !-------------------
> SUBROUTINE GETSTRING(str)
> !DEC$ ATTRIBUTES DLLEXPORT::GETSTRING
> CHARACTER(LEN=*) :: str
> WRITE(*,*) 'I am in Fortran'
> !DEC$ ATTRIBUTES REFERENCE :: str
> str = 'String from FORTRAN'
> END SUBROUTINE GETSTRING
> 
> /* C# Import */
> [ DllImport( "TestExport.dll" )]
> public static extern void GETSTRING([In,Out]string strMessage);

Your problem is right here -------------------^

When unmanaged code is modifying a string reference you need to use
System.Text.StringBuilder, not string, so your C# code _should_ be:

	[DllImport ("TextExport")]
	public static extern void GETSTRING (
		[In, Out] System.Text.StringBuilder strMessage);

	static void Main (string[] args)
	{
		System.Text.StringBuilder str = 
			new System.Text.StringBuilder (1024);
		str.Append ("String from C#");
		GETSTRING (str);
		Console.WriteLine (str);
		Console.WriteLine ("Finished call to Fortran");
	}

Also, it would be a good idea for you to modify GETSTRING to accept a
buffer length argument, so that you don't overflow the string buffer:

	GETSTRING (str, str.Capacity);

 - Jon




More information about the Mono-devel-list mailing list