【问题标题】:c++ to csharp string passing with dllimport , lost accentsc++ 到 csharp 字符串通过 dllimport 传递,丢失重音
【发布时间】:2018-07-18 09:00:34
【问题描述】:

我正在尝试从 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);

【问题讨论】:

  • 您需要开始使用正确的文本编码。通常首选 Unicode 编码 UTF8。 UTF16 可能更方便。
  • 你能解释一下怎么做吗?谢谢
  • 周围有很多例子。尝试一些研究。

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


【解决方案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#代码:

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

【讨论】:

  • 没有。这是内存泄漏。而且 C++ 代码不会产生 UTF8 编码的数据。
  • 它对我有用,我成功地掌握了我的口音。我还认为 stackoverflow 是为了帮助人们而不仅仅是告诉他们他们错了。我花了几个小时寻找解决方案,所以没有“周围没有很多例子”可以做我想做的事情。所以谢谢你不帮忙,我希望我的回答能帮助别人
  • 这对任何人都没有帮助。
猜你喜欢
  • 1970-01-01
  • 2016-11-12
  • 1970-01-01
  • 2014-08-11
  • 2017-07-25
  • 2016-07-05
  • 2012-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多