How to pass a string containing extended ascii chracters to an unmanaged C++ dll

c#, marshalling, unmanaged

Solution

Have you tried:

[DllImport("c:\\USBPD.DLL")]
private static extern int WriteText([In] byte[] text, int length);

public static int WriteText(string text)
{
    Encoding enc = Encoding.GetEncoding(437); // 437 is the original IBM PC code page
    byte[] bytes = enc.GetBytes(text);
    return WriteText(bytes, bytes.Length);
}

Note that EntryPoint is not necessary if the name of the method is the same.

Problem

I have a C# application that talks to a USB peripheral through a C DLL. The C DLL implements a function : ``` long WriteText(char* data, long length); ``` If calling this from C/C++ I can send it regular ASCII text but also some extended characters such as '£' (0x9C hex). However, I have wrapped this up in a C# class ``` [DllImport("c:\\USBPD.DLL", EntryPoint = "WriteText")] public static extern int WriteText(string data, int length); ``` However, when I send it a string with a "£" I get a 'u^' in it's place. The rest of the string is fine. I have played around with the encoding types but still seem to be having problems. Thank Anand

Original source