1

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)?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.