简体   繁体   中英

byte[] array from unmanaged memory

I'm writing a simple .NET wrapper to C/C++ Pylon library for Basler cameras under linux (Ubuntu) in monodevelop. I'm building a .so (.dll) file in Code::Blocks and P/Invoke it in monodevelop. I have two simple tasks: get a single image and get a sequence of images.

I managed the first part in this way:

in C++ i have a function:

void GetImage(void* ptr)
{
    CGrabResultPtr ptrGrabResult;
    //here image is grabbing to ptrGrabResult
    camera.GrabOne(5000,ptrGrabResult,TimeoutHandling_ThrowException);
    //i'm copying byte array with image to my pointer ptr
    memcpy(ptr,ptrGrabResult->GetBuffer(),_width*_height);

    if (ptrGrabResult->GrabSucceeded())
        return;
    else
        cout<<endl<<"Grab Failed;"<<endl;
}

and in C#:

[DllImport("libPylonInterface.so")]
private static extern void GetImage(IntPtr ptr);

public static void GetImage(out byte[] arr)
{
    //allocating unmanaged memory for byte array
    IntPtr ptr = Marshal.AllocHGlobal (_width * _height);
    //and "copying" image data to this pointer
    GetImage (ptr);

    arr = new byte[_width * _height];
    //copying from unmanaged to managed memory
    Marshal.Copy (ptr, arr, 0, _width * _height);
    Marshal.FreeHGlobal(ptr);
}

and after that i can build an image from this byte[] arr .

I have to copy a huge amount of bytes twice (1. in c++ memcpy() ; 2. in c# Marshal.Copy() ). I tried to use a direct pointer to image buffer ptr = ptrGrabResult -> GetBuffer() , but get a mono environment error, when marshalling bytes.

So here is a question: is it a fine solution? Am i going in right direction?

PS Give me please some advices how should i manage with image sequence?

You can get the marshaller to do the work for you. Like this:

[DllImport("libPylonInterface.so")]
private static extern void GetImage([Out] byte[] arr);

....

arr = new byte[_width * _height];
GetImage(arr);

This avoids the second memory copy because the marshaller will pin the managed array and pass its address to the unmanaged code. The unmanaged code can then populate the managed memory directly.

The first copy looks harder to avoid. That is probably forced upon you by the camera library that you are using. I would comment that you should probably only perform that copy if the grab succeeded.

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