Reputation: 1522
When I use IntPtr to reserve memory and pass a dynamic array to native code, after I initialize this memory on the C#/managed side and pass it to my native DLL, is this chunk of memory pinned or copied? I.e. if I modify the array within my native code, will I see the modifications back in my managed code?
I know it is not necessary to use IntPtr, but since the array is embedded into a complex struct, it seems more convenient.
Upvotes: 1
Views: 136
Reputation: 942538
The only valid ways to obtain an IntPtr for a memory allocation in a .NET program are:
Be very careful with the latter two bullets, especially with the fixed keyword which requires unsafe since it is dangerous. Very important to stop using the IntPtr once code execution leaves the scope of the fixed statement. Not enforced by the runtime, the failure mode is a completely undiagnosable ExecutionEngineException when the GC discovers that the heap got corrupted. Caused by code writing through the IntPtr into the memory block after it got moved, thus overwriting something else.
Upvotes: 2