why do these 2 ways of invoking an external C function work?

  • Thread starter Thread starter Ted Sung
  • Start date Start date
T

Ted Sung

Hi,

I'm using P/Invoke to call a C function from a DLL in my C# class.
My C function is this

char * icmo_version_chk( const char *version )

I've tested both these declarations and both work.

public static extern IntPtr icmo_version_chk(
[MarshalAs(UnmanagedType.LPStr)] string version );

string sVer = "3.0f_p2";
IntPtr test = icmo_version_chk( sVer );
string sRetVer = Marshal.PtrToStringAnsi(test);
Console.WriteLine( "The version loaded via DllImport is " + sRetVer ) ;

or

public static extern IntPtr icmo_version_chk( StringBuilder sVer );

StringBuilder sVer = new StringBuilder("3.0f_p2");
IntPtr test = icmo_version_chk( sVer );
string sRetVer = Marshal.PtrToStringAnsi(test);
Console.WriteLine( "The version loaded via DllImport is " + sRetVer ) ;


It was my understanding that in order to map from C# to C's const char *,
I needed to marshal the parameter as in the first example. However,
the second declaration works as well and I'm wondering why.
 
It was my understanding that in order to map from C# to C's const char *,
I needed to marshal the parameter as in the first example. However,
the second declaration works as well and I'm wondering why.

A StringBuilder is used for output or in/out string buffers. String
should only be used for const input-only arguments like in this case.
It should work even without the explicit MarshalAs attribute.



Mattias
 
Back
Top