系统.在c#上从c++获取字符串数组时出现OutOfMemoryException

System.OutOfMemoryException when getting string array from c++ on c#

本文关键字:数组 OutOfMemoryException 字符串 获取 上从 c++ 系统      更新时间:2023-10-16

我的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发生"

知道为什么吗?

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