c ++使用dllimport传递csharp字符串,丢失重音符号

时间:2018-02-07 22:40:09

标签: c# c++ dll utf-8 dllimport

我正在尝试从c ++向csharp发送消息,但是我的一些口音在路上丢失了(不是全部?)ps:从意大利语写作

这是我做的: c ++:

#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif

extern "C" {
    DLL_API void __cdecl getResults(char* entry, wchar_t* result);
} 

[...]

void getResults(char* entry,wchar_t* result)
{
std::string str(entry);
std::string Stringresult= "héà" ;
std::wstring wsTmp(Stringresult.begin(), Stringresult.end());
const wchar_t* constChar = wsTmp.c_str();
swprintf(result, Stringresult.length(), constChar);

c#:

    [DllImport("libface.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
    public static extern void getResults([MarshalAs(UnmanagedType.LPStr)] string entry, StringBuilder res);



    static void Main()
    {
        StringBuilder result = new StringBuilder(2000);


        string entry = Console.ReadLine();
        getResults( entry,result);
        Console.WriteLine(result);

1 个答案:

答案 0 :(得分:-1)

通过这个链接解决了这个问题(这说明问题比某些人想象的要复杂得多......):

http://blog.kutulu.org/2012/04/marshaling-utf-8-harder-than-it-ought.html

c ++代码:

extern "C" {
    DLL_API char* __cdecl getResults(char* entry);
}
char* getResults(char* entry)
{
   std::string Stringresult= "hàé";
   char *cstr = new char[Stringresult.length() + 1];
   strcpy(cstr, Stringresult.c_str());
   return cstr;
}

c#c​​ode:

[DllImport("libface.dll" , EntryPoint = "getResults")]
private static extern IntPtr getResults([MarshalAs(UnmanagedType.LPStr)] string entry);

static void Main()
{
  var data = new List<byte>();
 var ptr = getResults("p");
 var off = 0;
 while (true)
 { 
    var ch = Marshal.ReadByte(ptr, off++);
    if (ch == 0)
    {
      break;
    }
    data.Add(ch);
 }
  string sptr = Encoding.UTF8.GetString(data.ToArray());
  Console.WriteLine(sptr);