问题描述
- C#中调用C++Dll接口,字符串编码问题
-
在C#中调用C++Dll接口,接口返回一个多字节字符串,然后再C#中再次转码为宽字节字符串。
字符串内容都为汉字。**_问题:
如果汉字为偶数个,则一切正常; 如果汉字为奇数个,则C#获得的多字节字符串内容的最后一个字节被篡改成‘?’的ascll码。(多字节编码时,每个汉字占三个字节) 本人没多少币,全部家当拿出来了,求大神指点。**_
C++代码:
// 宽字节转多字节
__declspec(dllexport) void TCharToChar(LPCWCH tchar, char * _char)
{
//获取字节长度
int iLength = WideCharToMultiByte(CP_UTF8, 0, tchar, -1, NULL, 0, NULL, NULL);
//将tchar值赋给_charWideCharToMultiByte(CP_UTF8, 0, tchar, -1, _char, iLength, NULL, NULL);
}// 多字节转宽字节
__declspec(dllexport) void CharToTChar(char* _char, LPWSTR tchar)
{
int iLength = MultiByteToWideChar(CP_UTF8, 0, _char, -1, NULL, 0);
MultiByteToWideChar(CP_UTF8, 0, _char, -1, tchar, iLength);
}__declspec(dllexport) char* GetStr()
{
setlocale(LC_ALL, "chs");LPCWCH pTChar = L"好"; char* pChar = new char[50]; memset(pChar, 0, 50); TCharToChar(pTChar, pChar); return pChar;
}
C#代码:
class Program
{
private const string strDllPath = "DllTest.dll";[DllImport(strDllPath, EntryPoint = "GetStr", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] extern public static IntPtr GetStr(); // 多字节转宽字节 [DllImport(strDllPath, EntryPoint = "CharToTChar", CallingConvention = CallingConvention.Cdecl)] extern public static void CharToTChar(string src, [MarshalAs(UnmanagedType.LPWStr)]string des); // 宽字节转多字节 [DllImport(strDllPath, EntryPoint = "TCharToChar", CallingConvention = CallingConvention.Cdecl)] extern public static void TCharToChar(string src, StringBuilder des); static void Main(string[] args) { IntPtr ptr = GetStr(); string str = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(ptr); bytes = System.Text.Encoding.Default.GetBytes(str); string strResult = System.Text.Encoding.Default.GetString(bytes); Console.WriteLine(strResult); }
}
解决方案
C#调用C++DLL时的编码转换-编码、字符集
C#调用C++Dll字符串返回为空的问题
时间: 2024-10-07 19:28:36