dimanche 19 juin 2016

How to pass C# object references to and from C++


Is there any way to pass C# object references (class types, not structs) into and out of C++ via native interop?

Here's my use case:

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.

The question is: what's the best way to associate objects in C# with the corresponding physical bodies in C++?

I can think of a couple ways:

  1. 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.
  2. 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.
  3. Find some other way to refer to C# objects in C++ and associate that reference with each native physical body.

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.


Aucun commentaire:

Enregistrer un commentaire