资质愚钝的菜鸟 2015-11-16 08:45 采纳率: 0%
浏览 3910
已结题

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值赋给_char

WideCharToMultiByte(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);
}

}

  • 写回答

1条回答

  • qu_yiming 2017-08-15 07:18
    关注

    兄弟,这个问题解决了吗?

    评论

报告相同问题?

悬赏问题

  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?