简体   繁体   English

如何在非托管内存中分配IntPtr []数组?

[英]How to allocate array of IntPtr [] in unmanaged memory?

To allocate memory in managed code i use: 要在托管代码中分配内存,我使用:

IntPtr [] params_list_n = new IntPtr [5];

But for unmanaged memory i use Marshal.AllocHGlobal And I do not understand how, in this case to allocate memory for the array. 但对于非托管内存我使用Marshal.AllocHGlobal我不明白如何为这个数组分配内存。

Ideally I want to use the function call Marshal.GetNativeVariantForObject (o, params_list_n[i]); 理想情况下,我想使用函数调用Marshal.GetNativeVariantForObject (o, params_list_n[i]); For each element of the array. 对于数组的每个元素。

Creating unmanaged memory using Marshal.AllocHGlobal is simple. 使用Marshal.AllocHGlobal创建非托管内存非常简单。

IntPtr pointer = Marshal.AllocHGlobal(1024);

If you need to calculate the amount of space you can use Marshal.SizeOf . 如果您需要计算空间量,可以使用Marshal.SizeOf

int size = Marshal.SizeOf(typeof(IntPtr));
IntPtr pointer = Marshal.AllocHGlobal(size);

You will also need to enable unsafe code in your project for this to run. 您还需要在项目中启用unsafe code才能运行此unsafe code

  1. Right click on your project and select Properties . 右键单击您的项目,然后选择“ Properties
  2. Open the Build tab. 打开“ Build选项卡。
  3. Select Allow unsafe code . 选择Allow unsafe code

The array will be a pointer to the elements. 该数组将是指向元素的指针。 You use it the same way: 你以同样的方式使用它:

IntPtr results = Marshal.AllocHGlobal(5 * IntPtr.Size);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM