如何将 unicode 字符串从 c# 传输到 c/c++ dll
How to transfer unicode string from c# to c/c++ dll
我从 C# 调用了一个 C/C++ DLL 函数,当函数有 wchar_t* parameter
.
时出现问题
我把参数从wchar_t*
改成了char*
,然后就ok了
为什么?如何让它与 wchar_t*
一起工作?
这是我的代码:
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++代码:
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**
}
因为我需要使用wchar_t*
,如何解决?
您可能需要告诉编组器如何传输委托的 str
参数:
delegate void DllTestFunc([MarshalAs(UnmanagedType.LPWStr)] string str, byte[] data, int length);
我从 C# 调用了一个 C/C++ DLL 函数,当函数有 wchar_t* parameter
.
时出现问题
我把参数从wchar_t*
改成了char*
,然后就ok了
为什么?如何让它与 wchar_t*
一起工作?
这是我的代码:
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++代码:
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**
}
因为我需要使用wchar_t*
,如何解决?
您可能需要告诉编组器如何传输委托的 str
参数:
delegate void DllTestFunc([MarshalAs(UnmanagedType.LPWStr)] string str, byte[] data, int length);