分配“非托管" C#中的内存

分配“非托管

问题描述:

我正在c#中编写一个使用C ++库的程序,由于某种原因,我需要分配一个非托管缓冲区以将其传递给lib.有没有办法在C#中做到这一点? 基本上我只需要在C#中做一个malloc ...

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#...

谢谢

尝试如下操作:

using System;
using System.Runtime.InteropServices;

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

这使用 Marshal.AllocHGlobal 方法:

This uses the Marshal.AllocHGlobal method:

使用指定的字节数从进程的非托管内存中分配内存.

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