How to allocate array of IntPtr [] in unmanaged memory?
Asked Answered
A

2

5

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.

Ideally I want to use the function call Marshal.GetNativeVariantForObject (o, params_list_n[i]); For each element of the array.

Abrade answered 24/3, 2013 at 22:33 Comment(0)
T
8

Creating unmanaged memory using Marshal.AllocHGlobal is simple.

IntPtr pointer = Marshal.AllocHGlobal(1024);

If you need to calculate the amount of space you can use 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.

  1. Right click on your project and select Properties.
  2. Open the Build tab.
  3. Select Allow unsafe code.
Thoughtless answered 24/3, 2013 at 22:39 Comment(1)
Thank you. Tell me more how to copy the memory from unmanaged to unmanaged. Marshal.Copy not be suitable for this purpose. As I understandAbrade
D
4

The array will be a pointer to the elements. You use it the same way:

IntPtr results = Marshal.AllocHGlobal(5 * IntPtr.Size);
Dentiform answered 24/3, 2013 at 22:39 Comment(3)
@Abrade fixed - sorry, went fastDentiform
I forgot about IntPtr.Size. Kudos. :)Thoughtless
Thank you. But I can not access the individual elements of the array. This is not quite what I need. I want to use the function call Marshal.GetNativeVariantForObject (o, params_list_n[i]); For each element of the array.Abrade

© 2022 - 2024 — McMap. All rights reserved.