简体   繁体   中英

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. I want to pass it to C#, but I'm not sure how. 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. I've tried using strlen, but that just returns 0.

Here is my C++ code:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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