系统.在c#上从c++获取字符串数组时出现OutOfMemoryException
System.OutOfMemoryException when getting string array from c++ on c#
我的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,它允许您提供要复制的字符数。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '