title: How to pass C# object references to and from C++
body: <p>Is there any way to pass C# object references (class types, not structs) into and out of C++ via native interop?</p>
  
  <p>Here's my use case:</p>
  
  <p>I'm trying to write a game engine in C# but want to use a native (C++) physics library. The physics library maintains its own internal state of all the physical bodies and lets the user associate a small amount of data (a pointer) with each body. After a physics simulation tick, the library supplies a list of all physical bodies that moved. I want to iterate over this list and relay all the changes to the corresponding C# objects.</p>
  
  <p>The question is: what's the best way to associate objects in C# with the corresponding physical bodies in C++?</p>
  
  <p>I can think of a couple ways:</p>
  
  <ol>
  <li>Give each physical body an ID of some kind, associate the ID with the physical body in C++, and maintain a map of ID's to corresponding objects in C#. This seems unnecessarily indirect to me, even with an optimized mapping mechanism.</li>
  <li>Take advantage of the ability to marshal C# delegates (which can implicitly reference C# object instances) into C++ function pointers. This might be the best way to do it; I don't know how C# implements delegates and what type of overhead this would entail.</li>
  <li>Find some other way to refer to C# objects in C++ and associate that reference with each native physical body.</li>
  </ol>
  
  <p>Is there any mechanism like option 3 I don't know of? C++/CLI isn't an option since I want to support platforms without it.</p>