镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Use System.Runtime.InteropServices.NativeMemory on modern .NET #99

Description

@CurtHagenlocher

Describe the enhancement requested

Use System.Runtime.InteropServices.NativeMemory on modern .NET. AlignedAlloc and AlignedFree seem particularly useful for Arrow buffers.

Instead of using #if regions to distinguish between flavors of .NET, a better approach might be to create a NativeMemory-compatible wrapper for downlevel versions that front-ends something like the existing code.

Activity

  1. CurtHagenlocher commented on Mar 20, 2026

    @CurtHagenlocher
    ContributorAuthor

    Can also use the following on older .NET:

    internal static class AlignedMalloc
    {
        // Allocate aligned memory
        [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl)]
        internal static extern IntPtr _aligned_malloc(
            UIntPtr size,
            UIntPtr alignment);
    
        // Free aligned memory
        [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl)]
        internal static extern void _aligned_free(
            IntPtr memblock);
    
        // Optional: reallocate aligned memory
        [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl)]
        internal static extern IntPtr _aligned_realloc(
            IntPtr memblock,
            UIntPtr size,
            UIntPtr alignment);
    
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        static extern IntPtr LoadLibrary(string lpFileName);
    
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
    
        public static bool HasAlignedMalloc()
        {
            IntPtr h = LoadLibrary("ucrtbase.dll");
            if (h == IntPtr.Zero)
                return false;
    
            return GetProcAddress(h, "_aligned_malloc") != IntPtr.Zero;
        }
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions