Search code examples
c#memoryunmanaged

allocating "unmanaged" memory in c#


I'm writting a program in c# that uses a C++ library, and for some reason I need to allocate an unmanaged buffer to pass it to the lib. Is there a way to do this in c# ? Basically I would just need to do a malloc in C#...

Thanks


Solution

  • Try something like this:

    using System;
    using System.Runtime.InteropServices;
    
    class Example
    {
        static void Main()
        {
            IntPtr pointer = Marshal.AllocHGlobal(1024);
        }
    }
    

    This uses the Marshal.AllocHGlobal method:

    Allocates memory from the unmanaged memory of the process by using the specified number of bytes.