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

时间:2011-07-21 17:20:16

标签: c# c++ exception dll interop

我的C ++功能

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

我的C#签名是

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

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]);
}

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

任何想法为什么?

1 个答案:

答案 0 :(得分:2)

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