I am writing a unmanaged plugin and I am trying to return a custom class from c++ to C#, I don’t think it’s possible but I am trying to check:
//Character.h
TESTFUNCDLL_API Character MakeCharacter();
class Character
{
int health;
int magic;
public:
ReturnCharacterClass()
{
return *this;
}
}
//Character.cpp
Character MakeCharacter()
{
Character cCharacter;
return cCharacter.ReturnCharacterClass();
}
//UseDll.cs
[DllImport("Character", EntryPoint = "Character")]
//How do I refrence character?! -public static extern int character();
First of all C# / .NET classes are located in managed heap memory.
C# / .NET classes have a different memory layout and class / type system.
C++ uses namemangeling for all exported symbols. Every C++ compiler uses it’s own mangeling rules.
What you usually can do is:
passing native object references to C# and interpret them as IntPtr. You can’t do anything on the C# side with it beside passing it back to a native code method where the C++ code can use the class pointer. Keep in mind that allocated memory on the native side has to be managed by yourself.
Native plugins can use extern "C" to export static methods without name mangeling which can be used by managed code.
C# code can allocate and “pin” managed memory and pass a reference to an exported C method and fill that memory with data. Scope and extent of that memory has to be taken care of.
You are going to want to exchange the data as though you are writing a server/client. I don’t know if C# can interpret binary data, but I would definitely give it a shot. You could have a struct with your native types, return that, and cast it back into a similar struct in C#. You may get mismatches for size of things though.
A safer route is to exchange using json or bson. Just return a json representation as a string and parse that in Unity.