简体   繁体   中英

Marshalling dynamic array to C# delegate (callback)

I have some native C/C++ code that calls a C# delegate as callback. What's the best practice to pass a dynamic array argument? Actually the C pointer is a data member of a struct and I pass the struct to the callback.

Is it OK to do something like this using IntPtr ?

struct Data {
    ... (other data members)
    double* array;
    int size;
};

Array is a pointer to an array allocated in my C++ code (just a call to new or malloc ). On the C# side the delegate would expect

struct Data {
    ... (other data members)
    IntPtr array;
    int size;
}

My concern is... should IntPtr be memory allocated using Marshal.AllocHGlobal or is it also safe if it's memory allocated in my C++ code ( new or malloc )?

Using IntPtr is correct. The memory is allocated, and deallocate on the unmanaged side. You should therefore do nothing related to allocation and deallocation on the managed side.

Simply read from or write to the array using Marshal.Copy . Or if you prefer use an unsafe block and interpret the IntPtr as a double* .

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