Let's say I have some int sharedInt
that I need to share between managed C# code and a native C++ library. Both the C# and C++ code need to be able to read and write from/to sharedInt
.
My first solution was to allocate memory from C# using Marshal.AllocHGlobal()
, pass the IntPtr
to the C++ library as an int*
, and read/write to it using Marshal.ReadInt32()
and Marshal.WriteInt32()
. This worked, but the constant Marshal
calls slowed my application quite a bit.
My second solution was to simply declare the int
from C#, pass it as a ref int
to the C++ library, and read/write from it directly. This works for the first few calls, and then behaves unpredictably, often throwing an ExecutionEngineException
. Maybe the garbage collector is at fault?
How do I accomplish my goals? How do references to value types work in C#? Do I need to create some wrapper structure, and how do I properly pass it to C++?