Search code examples
c#c++dllpinvoke

How to transfer unicode string from c# to c/c++ dll


I call a C/C++ DLL function from C# and have a problem when the function has a wchar_t* parameter.
I modified the parameter from wchar_t* to char*, then everything is ok.
Why? how to make it work well with wchar_t*?

Here is my code:

C#

[DllImport("kernel32")]
private static extern IntPtr LoadLibraryEx(string fileName, IntPtr hFile, uint loadFlag);

[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr lib, string funcName);

[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr lib);

delegate void DllTestFunc(string str, byte[] data, int length);

static void Main(string[] args)
{   
    var dllInstance = LoadLibraryEx(@"D:\Development\NativeDll\x64\Debug\NativeDll.dll", IntPtr.Zero, 0x0008);
    var ptr = GetProcAddress(dllInstance, "DllTestFunc");
    var func = Marshal.GetDelegateForFunctionPointer<DllTestFunc>(ptr);
    var inputStr = @"E:\test.dat";
    var data = new byte[100];
    data[0] = 0x55;
    func(inputStr, data, 2020);
    FreeLibrary(dllInstance);
}

C/C++ Code:

void __stdcall DllTestFunc(wchar_t* str1, unsigned char* data, const int length)

{

    cout << str1 << endl;

    cout << int(data[0]) << endl;

    cout << length << endl;**strong text**

}

Because I need to use the wchar_t*, how to resolve it?


Solution

  • You probably need to tell the marshaller how to transfer the str argument of your delegate:

    delegate void DllTestFunc([MarshalAs(UnmanagedType.LPWStr)] string str, byte[] data, int length);