Closed
Description
API proposal
namespace System.Runtime.InteropServices
{
public static partial class Marshal
{
// Existing APIs
public static System.IntPtr AllocCoTaskMem(int cb);
public static System.IntPtr AllocHGlobal(int cb);
public static System.IntPtr AllocHGlobal(System.IntPtr cb);
public static void FreeCoTaskMem(System.IntPtr ptr);
public static void FreeHGlobal(System.IntPtr hglobal);
public static System.IntPtr ReAllocCoTaskMem(System.IntPtr pv, int cb);
public static System.IntPtr ReAllocHGlobal(System.IntPtr pv, System.IntPtr cb);
+ // Portable wrapper for C-runtime malloc
+ public static IntPtr AllocMemory(nint byteCount);
+ // Portable wrapper for C-runtime realloc
+ public static IntPtr ReAllocMemory(IntPtr ptr, nint byteCount);
+ // Portable wrapper for C-runtime free
+ public static void FreeMemory(IntPtr ptr);
+ // Portable wrappers for equivalent C-runtime method (Windows: _aligned_malloc, Posix: posix_memalign)
+ public static IntPtr AllocAlignedMemory(nint byteCount, int alignment);
+ public static void FreeAlignedMemory(IntPtr ptr);
}
}
Rationale
The alignment returned by Marshal.AllocHGlobal
may differ based on machine architecture and OS, see #33228. Some native APIs require specific memory alignment, some operations offer much better performance when the memory is aligned.
Example
IntPtr alignedAddr = Marshal.AllocAlignedMemory(16 * 32, 16);
Marshal.FreeAlignedMemory(alignedAddr);
Implementation
On posix platform, this may be implemented using posix_memalign.