Hi,
I am trying to write a wrapper in C# for the unmanaged code written in C++. Whats wrong in the following code.
C++ (Unmanaged Code)
extern int DllExport __stdcall GetName( LPSTR name)
{
name = "Smith, Allan";
strcat( name, "\0");
return strlen( name);
}
Wrapper Definition (Written in C#)
[DllImport("Unmanaged.Dll", SetLastError=true, ThrowOnUnmappableChar=true, EntryPoint="GetName)] public static extern int GetName( [MarshalAs(UnmanagedType.LPStr)] string name);
Wrapper function (written in C#)
public static int GetName( string name)
{
int rc;
rc = Wrapper.GetName( name);
return rc;
}
When I run this function, Wrapper.GetName function returns 12 (length of Smith, Allen). But the variable name is still blank.
Please help me.
Thanks
Raja

Unmanaged Code (written in C++) Interop with C#
Jublar
Use the CharSet in DllImport to enable ASCII format.
tinu44
Use System.Text.StringBuilder instead of string.
WebSnozz
Surely you need to pass your string in as a ref parameter ( whatever you need to do to the dll to make that work )
Eyfel
C++ (Unmanaged Code)
extern int DllExport __stdcall GetName( LPTSTR name)
{
name = "Smith, Allan";
strcat( name, "\0");
return strlen( name);
}
I had to declare "LPSTR name" as "LPTSTR name" in the above unmanaged function.
Wrapper Definition (Written in C#)
[DllImport("Unmanaged.Dll", SetLastError=true, ThrowOnUnmappableChar=true, EntryPoint="GetName)] public static extern int GetName( StringBuilder name);
I had to change the "[MarshalAs(UnmanagedType.LPStr)] string " to "StringBuilder"
Wrapper function (written in C#)
public static int GetName( string name)
{
int rc;
rc = Wrapper.GetName( name);
return rc;
}
I changed the above function to ...
public static int GetName( ref string name)
{
int rc;
StringBuilder sb = new StringBuilder( 256);
rc = Wrapper.GetName( sb);
name = sb.ToString( );
return rc;
}
It is working now. But I would like to know how it get it working with LPSTR...
Thanks for your help.
Raja
Pete A