C 到Csharp String与Dllimport通过,丢失的口音

c++ to csharp string passing with dllimport , lost accents

本文关键字:通过 Csharp String Dllimport      更新时间:2023-10-16

我试图将消息从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);

通过此链接解决了问题(该链接说明问题要复杂得多,而某些人可能会想到....(:

http://blog.kutulu.org/2012/04/marshaling-utf-8-harder-than-iat-ught.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#代码:

[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);