简体   繁体   English

如何将 CImg 图像对象从 C++/CLI 传递到 C#

[英]How Do I Pass a CImg Image Object from C++/CLI to C#

I have some C++/CLI code that creates a simple CImg image and draws a circle on it.我有一些 C++/CLI 代码,可以创建一个简单的 CImg 图像并在其上绘制一个圆圈。 I want to pass it to C#, but I'm not sure how.我想将它传递给 C#,但我不确定如何传递。 I thought of using a byte array to pass it to C#, but I can't get the length of the array, which is needed for any conversion from byte* to byte[] or for passing into the unmanaged memory stream.我想过使用字节数组将它传递给 C#,但我无法获得数组的长度,这是从 byte* 到 byte[] 的任何转换或传递到非托管内存流所需要的。 I've tried using strlen, but that just returns 0.我试过使用 strlen,但它只返回 0。

Here is my C++ code:这是我的 C++ 代码:

unsigned char* calculateFrame::ReadImage() {
    CImg<unsigned char> testImage(1920, 1080, 1, 3, 0);
    const unsigned char white[3] = { 255,255,255 };
    testImage.draw_circle(256, 256, 200, white, 1.0f, ~0U);
    testImage.draw_point(500, 500, white, 255);

    unsigned char* charArray = (unsigned char*)testImage;
    return charArray;
}

C# code: C#代码:

Bitmap testBmp;

        using(var test = new FrameCalculator.calculateFrame())
        {
            Console.WriteLine(test.calculateOneFrame(3));
            unsafe
            {
                byte* imageArray = test.ReadImage();
                using(var ms = new UnmanagedMemoryStream(imageArray , /* length of byte* (unknown) */))
                {
                    testBmp = new Bitmap(ms);
                }
            }
        }

If you have any tricks to get around unsafe code without sacrificing performance, that would be nice, but I'm not opposed to using unsafe code if it's necessary.如果您有任何技巧可以在不牺牲性能的情况下绕过不安全代码,那就太好了,但我不反对在必要时使用不安全代码。

I ended up deciding that in the future, I would need a frame buffer, which necessitated writing the frames to the disk, so that they weren't lost in a restart.我最终决定将来需要一个帧缓冲区,这需要将帧写入磁盘,以便它们不会在重新启动时丢失。

Anyways, my solution was to write the image to disk as a .BMP and access it using Image.FromFile in C#.无论如何,我的解决方案是将图像作为 .BMP 写入磁盘并使用 C# 中的 Image.FromFile 访问它。 This isn't a great way to do this in most cases, because it adds a lot of overhead, but it made sense in my program.在大多数情况下,这不是一个很好的方法,因为它增加了很多开销,但在我的程序中是有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM