gpt4 book ai didi

c# - 使用 C++/CLI 包装器返回位图

转载 作者:行者123 更新时间:2023-11-28 05:49:34 25 4
gpt4 key购买 nike

我尝试为 OpenCV 编写一个 CLI 包装器,它从给定的 OpenCV 矩阵返回一个位图。我在包装器中使用带有修复图像的函数来测试它:

Bitmap^ GetImage()
{
Mat frame = imread("Image.png", 0);
return gcnew Bitmap(frame.cols, frame.rows, 4 * frame.rows, System::Drawing::Imaging::PixelFormat::Format24bppRgb, IntPtr(frame.data));
}

我的 C# 代码包含以下用于存储图像的代码:

Bitmap Test = Wrapper.GetImage();
Test.Save(@"C:\temp\Bla.bmp");

执行代码后,我得到了这个异常:

http://i.stack.imgur.com/79lqW.png

我该如何解决?这个异常的原因是什么?

最佳答案

这行不通。因为当函数返回时,'frame' 变量超出范围。因此,指针已死,并且您有一个带有指向垃圾数据的指针的 GDI 对象。

https://msdn.microsoft.com/en-us/library/zy1a2d14(v=vs.110).aspx?cs-save-lang=1&cs-lang=cpp#code-snippet-1

The caller is responsible for allocating and freeing the block of memory specified by the scan0 parameter. However, the memory should not be released until the related Bitmap is released.

我不确定这个 Mat 对象是什么,但是你得到了字节的一维行并对预先分配的字节数组 (array^) 执行 Marshal::Copy()。

我要么返回这个从 Mat 对象创建的数组,然后像这样在 C# 中创建位图:

https://stackoverflow.com/a/21555447/887584

或者如果您想保持关注点分离,您当然可以在 C++ 代码中执行此操作,在 C++ 中执行相同的操作:

auto stream = gcnew MemoryStream(bytes);
auto bitmap = gcnew Bitmap(stream);
delete stream;
return bitmap;

关于c# - 使用 C++/CLI 包装器返回位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35541140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com