2012-02-20 23 views
0

我正在从C++发送一系列char arrays到我的C#程序。从C++编码到C#

的C++函数是这个样子:

ReturnChar.cpp

extern "C" RETURNCHAR_API char* testString() 
{ 
    return test; 
} 

ReturnChar.h

extern "C" RETURNCHAR_API char* __cdecl testString(); 

ReturnChar导入C#

public static class ImportTest 
    { 
     [DllImport("ReturnChar.dll", EntryPoint = "testString", CallingConvention = CallingConvention.Cdecl)] 
     public static unsafe extern char* testString(); 
    } 
    public partial class MainWindow : Window 
    { 
     public unsafe MainWindow() 
     { 
      InitializeComponent(); 
      try 
      { 

       StringBuilder sb = new StringBuilder(new string(ImportTest.testString())); 
       textBox1.Text = sb.ToString(); 
      } 
      catch(Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     } 
    } 

实际上我得到了结果,但看起来像在C++和C#之间存在编码问题。我该如何解决这个问题?

我不打算在我的C++程序中使用wchar_t,因为我的操作是在char数组上完成的。我可以用C#编码吗?

+0

[Interop从C#发送字符串到C++]的可能重复(http://stackoverflow.com/questions/683013/interop-sending-string-from-c-sharp-to-c) – 2012-02-20 07:07:57

回答

1

应该是使用wchar_t贯穿在你的C++程序,并在wchar_t阵列执行的操作来代替。

也就是说,您需要将CharSet = CharSet.Ansi添加到DllImport参数中。