资质愚钝的菜鸟 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
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?