Unmanaged Code (written in C++) Interop with C#

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





Answer this question

Unmanaged Code (written in C++) Interop with C#

  • Jublar

    >> But I would like to know how it get it working with LPSTR...

    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

    I had to make few changes to the above code. It is working now.

    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

    Sorry, I was wrong. I am passing the string argument as ref.

  • Unmanaged Code (written in C++) Interop with C#