How to allocate an IntPtr [] array 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.

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

+5
source share
2 answers

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 also need to enable it unsafe codein your project so that it starts.

  • Properties.
  • Build.
  • Allow unsafe code.
+6

. :

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

All Articles