簡體   English   中英

從 c# 上的 c++ 獲取字符串數組時出現 System.OutOfMemoryException

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

我的 C++ function

    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' 的未處理異常”

任何想法為什么?

鑒於您遇到的異常的性質,程序無法嘗試分配 memory,這發生在示例代碼Marshal.AllocHGlobal()Marshal.PtrToStringUni()的兩個位置。 因此,除非GetPropertyCount()以某種方式返回Int.MaxValue ,否則程序可能會失敗,因為wcsncpy不會 null 終止復制的字符串。 因此,對Marshal.PtrToStringUni()的調用正在分配您機器的所有 memory 試圖確定復制的字符串實際結束的位置。 嘗試使用允許您提供要復制的字符數的PtrToStringUni API。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM