C# 在C+中创建和使用System.Drawing.Bitmap+/CLI

C# 在C+中创建和使用System.Drawing.Bitmap+/CLI,c#,c++-cli,gdi+,C#,C++ Cli,Gdi+,我试图在C++/CLI中完成以下任务 我有一个构建图像(位图)内容的本机类: 我想使用此数据创建托管System.Drawing.Bitmap。我的第一个想法是使用构造函数: Bitmap( int width, int height, int stride, PixelFormat format, IntPtr scan0 ) 我觉得这有点可行,但现在遇到了一些问题,以后使用此位图会导致System.Drawing中出现首次异常System.AccessViolationExcept

我试图在C++/CLI中完成以下任务

我有一个构建图像(位图)内容的本机类:

我想使用此数据创建托管System.Drawing.Bitmap。我的第一个想法是使用构造函数:

Bitmap(
int width, 
int height, 
int stride, 
PixelFormat format, 
IntPtr scan0
)
我觉得这有点可行,但现在遇到了一些问题,以后使用此位图会导致System.Drawing中出现首次异常System.AccessViolationException。我怀疑问题在于我没有正确管理非托管位图位(由本机方法返回)到将其传递到托管位图构造函数的转换

我应该如何从第一个函数获取本机指针并准备它(例如,我是否需要使用interior_ptr或pin_ptr?)并将其传递给需要IntPtr的位图构造函数

编辑:详细说明一下,以下是我天真的尝试:

virtual void OnPaint(PaintEventargs^ e) override
{
...
   unsigned char* bits = nativeClassObj->getBitmapBits();

   gcnew Bitmap(width, height, stride, PixelFormat::Format24bppRgb, (IntPtr)bits);

   e->Graphics->DrawImage((System::Drawing::Image^)managedBitmap,0,0);
...
}
。。结果(我在绘图窗口中得到一个“红色X”):


不需要什么特别的东西,它需要一个指向非托管内存的指针。明显的故障模式是无法正确猜测位图构造函数参数,并且在使用位图时无法保持指针稳定。“没有明显的方法来说明它不再使用了。@HansPassant后者可能是个问题-你能告诉我如何保持指针稳定吗?”?我是C++的新成员。我尝试使用PixPtR作为本地指针,但没有运气。这取决于您的本机C++类的API。指向位的指针必须在位图的整个生命周期内有效;位图不会自行复制图像数据。
virtual void OnPaint(PaintEventargs^ e) override
{
...
   unsigned char* bits = nativeClassObj->getBitmapBits();

   gcnew Bitmap(width, height, stride, PixelFormat::Format24bppRgb, (IntPtr)bits);

   e->Graphics->DrawImage((System::Drawing::Image^)managedBitmap,0,0);
...
}
A first chance exception of type 'System.AccessViolationException' occurred in System.Drawing.dll