2012-09-24 53 views
1

我需要調用一個使用C#中多字節字符集的函數(c/C++)。但我不知道如何將它編組爲多字節。有誰知道如何將結果轉換爲字符串?如何編組多字節字符集C#

C#:

[DllImport("essentials.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] 
     public static extern System.IntPtr GetFiles(string filedir, string path); 

     [STAThread] 
     static void Main() 
     { 
      string filedir = @"C:\Users\Ruben\Documents\School\*"; 
      string path = @"C:\Users\Ruben\Documents\School\"; 
      System.IntPtr pointer = GetFiles(filedir, path); 
      string files = Marshal.PtrToStringAnsi(pointer); // nothing 
     } 

C++

MSDN上
extern "C" 
{ 
    __declspec(dllexport) char* GetFiles(char* filedir, char* path) 
    { 
     string filedir2 = filedir; 
     string path2 = path; 
     string files = GetFiles2(filedir2, path2); 
     char* Rfiles = new char[files.length() + 1]; 
     strcpy_s(Rfiles, files.length() + 1, files.c_str()); 
     return Rfiles; 
    } 
} 
+0

使用調試器來調試你的nati ve代碼。一種解釋是該字符串只是空的。你不能拼湊這個代碼,你分配的char []不能再次被刪除。 –

回答

0

您需要這位名帥的C#字符串首先,試試這個:

[DllImport("essentials.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] 
    public static extern System.IntPtr GetFiles 
     ([MarshalAs(UnmanagedType.AnsiBStr)]string filedir, 
     [MarshalAs(UnmanagedType.AnsiBStr)]string path); 
相關問題