GameObject/Component are classes, and they contain references to other classes. According to :
“The general rule of advice is this: never pass classes or structures containing members of reference type (classes) to unmanaged code. This is because unmanaged code can’t do anything safely with the unmanaged reference (pointer), and the CLI runtime doesn’t do a “deep marshal” (marshal members of marshaled classes, and their members, ad infinitum).”
As another problem, the same page also states:
“There are two other issues with classes. First of all, classes by default use LayoutKind.Auto layout. This means that the ordering of class data members is unknown, and won’t be determined until runtime. The runtime can rearrange the order of members in any way it chooses, to optimize for access time or data layout space. As such, you MUST use the StructLayout attribute and specify a LayoutKind value of LayoutKind.Sequential or LayoutKind.Explicit.”
But, Unity’s docs (AFAICS) don’t make any mention anywhere of what layout is used for any of Unity’s classes.
So how can I pass GameObject/Component to/from native plugin and access it from there?
It sounds almost impossible (I really hope not, because Unity’s editor seems fantastic, but I don’t like C#, JS or Boo). But this Unite 2013 video suggests a possible ray of hope:
Near the beginning of that, he says that’s Unity’s engine is really written in C++ and that Mono is just on top of that for scripting. He even suggests that Unity is already (somehow) bypassing all the marshaling on the border between Mono and Unity’s internal core.
So can I somehow take advantage of that, too? Does it mean that GameObject, Component and the other classes are really just C++ classes under-the-hood? If so, does it mean I can just simply pass a pointer to them from C# into my unmanaged plugin and use it as a pointer to a C++ class, therefore bypassing all that marshaling mess? If so, how can I find out the layout (because the docs don’t show the order of the members)? But if not, then how do I access such classes from an unmanaged plugin?