0

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

directquest
  • 130
  • 10
  • Does this answer your question? [sharing memory between two applications](https://stackoverflow.com/questions/7894224/sharing-memory-between-two-applications) – Mondonno Nov 04 '21 at 18:30
  • I'm not talking about two separate applications, I have a C# application which P/Invokes C++ functions through `DllImport`. – directquest Nov 04 '21 at 18:37
  • can't you than create a function that returns that variable? – Mondonno Nov 04 '21 at 18:39
  • Yes, but the repeated invocations would make this even slower than my first solution. – directquest Nov 04 '21 at 18:44
  • Basically both the C# and C++ code need to read/write on this variable millions of times on a different thread. I need something with minimal overhead. – directquest Nov 04 '21 at 18:46
  • The following may be helpful: https://learn.microsoft.com/en-us/windows/win32/ipc/named-pipes#:~:text=A%20named%20pipe%20is%20a,one%20or%20more%20pipe%20clients.&text=Named%20pipes%20can%20be%20used,different%20computers%20across%20a%20network and https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-use-named-pipes-for-network-interprocess-communication – Tu deschizi eu inchid Nov 04 '21 at 19:04
  • If you need to hold onto the memory between calls to the native C++, call `Marshal.AllocHGlobal` once and store the pointer – Charlieface Nov 04 '21 at 20:44
  • 1
    `ref int` in C# is compatible with `int*` in C/C++ and `int&` in C++. That alone should not be causing an `ExecutionEngineException`. Something else is going on. Please provide a [mcve] that demonstrates the problem in action. – Remy Lebeau Nov 04 '21 at 21:51

0 Answers0