从c#上的c ++获取字符串数组时出现System.OutOfMemoryException

Ass*_*saf 12 c# c++ dll interop exception

我的C++功能

    void FillArray(wchar_t** arr)
    {
         // some code
         for(i= 0;i<end;++i)
         {
             wcsncpy(arr[i],InforArray[i],MaxLength);
             count++;
         } 
     }
Run Code Online (Sandbox Code Playgroud)

我的C#签名是

[DllImport("Native.dll", CharSet = CharSet.Unicode,EntryPoint = "FillArray")]
        internal static extern void FillArray(
            [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPWStr)] 
            IntPtr[] OutBuff);
Run Code Online (Sandbox Code Playgroud)

而C#代码本身:

int maxLen = 256;


int count = GetPropertyCount(ref eData);
IntPtr[] buffer = new IntPtr[count];
for (int i = 0; i < count; i++)
     buffer[i] = Marshal.AllocHGlobal(maxLen);

FillArray(buffer);

string[] output = new string[count];

for (int i = 0; i < count; i++)
{
      output[i] = Marshal.PtrToStringUni(buffer[i]); 
      Marshal.FreeHGlobal(buffer[i]);
}
Run Code Online (Sandbox Code Playgroud)

在c ++循环中填充的数据没有任何问题,但是当退出FillArray时,我得到"发生了'System.OutOfMemoryException'类型的未处理异常"

有什么想法吗?

Cla*_*ton 2

鉴于您遇到的异常的性质,程序无法尝试分配内存,这发生在示例代码Marshal.AllocHGlobal()Marshal.PtrToStringUni(). 因此,除非GetPropertyCount()以某种方式返回Int.MaxValue,否则程序可能会失败,因为wcsncpy不会以 null 终止复制的字符串。因此,调用Marshal.PtrToStringUni()是分配所有机器的内存,试图确定复制的字符串实际结束的位置。尝试使用PtrToStringUni API,它允许您提供要复制的字符数。