C++ Wrapper for Unity

Hello,
I have a lot of code in C++ that I have to use somehow in C#. I’ve written a wrapper that works fine when I’m using it via C# project in Visual Studio, so I’m trying to use it with Unity.

I’ve copied the DLL to Plugins folder and it indeed recognizes the headers, since When I’m writing code in Unity suggestions pop-up with all the functions I coded in C++. When I try to compile and run it throws me this error:

MissingMethodException: Method contains unsupported native code
<Module>.<CrtImplementationDetails>.LanguageSupport._Initialize (<CrtImplementationDetails>.LanguageSupport* )
<Module>.<CrtImplementationDetails>.LanguageSupport.Initialize (<CrtImplementationDetails>.LanguageSupport* )
Rethrow as ModuleLoadException: The C++ module failed to load.
<Module>.<CrtImplementationDetails>.ThrowModuleLoadException (System.String errorMessage, System.Exception innerException)
<Module>.<CrtImplementationDetails>.LanguageSupport.Initialize (<CrtImplementationDetails>.LanguageSupport* )
<Module>..cctor ()
Rethrow as TypeInitializationException: An exception was thrown by the type initializer for <Module>
WrapperE.Start () (at Assets/WrapperE.cs:20)

First I thought it was because I was not targeting the framework of Unity, so I changed it to target .NET framework 2.0, which still works fine when using in a C# project in Visual Studio, but it still throws me the error above.

Many Thanks!

Do you have unity pro?

Yes

Make sure that your native functions are exposed in a C-style API:

Are you using any C++/CLI or unsafe code blocks? Neither will work with Unity.

I tried both. Is there any other way to make it work? If so, can you provide me an example/tutorial/documentation on what I need to do?

You need to use the Native Plugin (P/Invoke) approach that Thinksquirrel linked to in the post above mine. You’ll build your C++ code (not C++/CLI) as a DLL, and then write a C#-side wrapper with ‘extern’ functions that map to functions in the DLL.

1 Like

Unsafe code works fine in Unity, you just have to enable its usage explicitly passing -unsafe parameter to the compiler.

C++/CLI, like any other .Net language, works as well, but it has to be safe.