2011-02-06 54 views
1

我有一個C的DLL文件++函數(它被編譯與多字節字符集選項):封送非託管的char **託管的String []

_declspec(dllexport) void TestArray(char** OutBuff,int Count,int MaxLength) 
{ 
    for(int i=0;i<Count;i++) 
    { 
     char buff[25]; 
     _itoa(i,buff,10); 

     strncpy(OutBuff[i],buff,MaxLength); 
    } 
} 

我假設C#原型必須是下一個:

[DllImport("StringsScetch.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] 
    private static extern void TestArray([MarshalAs(UnmanagedType.LPArray)] IntPtr[] OutBuff, int Count, int MaxLength); 

但我應該準備的IntPtr對象以接收來自非託管代碼串?

+1

我不能用StringBuilder []來解決它。除了通過Marshal.AllocHGlobal編組以外,別無他法。 – 2011-02-06 18:35:46

+0

是的,這種方法正在工作!萬分感謝! – 2011-02-06 19:07:18

回答

4

所以OutBuff基本上是一個指針數組 - 所以你需要創建一個IntPtr數組,它的元素是有效的指針 - 也就是指向有效內存的IntPtr值。如下所示:

int count = 10; 
int maxLen = 25; 
IntPtr[] buffer = new IntPtr[count]; 

for (int i = 0; i < count; i++) 
    buffer[i] = Marshal.AllocHGlobal(maxLen); 

TestArray(buffer, count, maxLen); 

string[] output = new string[count]; 
for (int i = 0; i < count; i++) 
{ 
    output[i] = Marshal.PtrToStringAnsi(buffer[i]); 
    Marshal.FreeHGlobal(buffer[i]); 
}