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

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.
 
M

Mattias Sjögren

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top