Example exporting CPP class as DLL and importing in Unity C# as native plugin
There will be times when you want to run your C++ code inside Unity. So you will need to export the code into DLL format and then import it in Unity. This project is showing you an example of exporting a Student class written in C++, and import it in Unity C#.
Open Unity project TestImportCPPClass
and press Play button or Ctrl+P. You will see the output is being printed in the console.
Then take a look at TestImportCPPClass/Assets/TestImportCPPClass.cs to see how it is implemented. You will see quickly that it's just a bunch of function calls to the DLL files.
-
Open Visual Studio 2017 and create a new DLL project.
-
Copy content of file
TestExportCPPClass.cpp
fromTestExportCPPClass/TestExportCPPClass/
directory. -
Go to Build -> Build solution, make sure the build is set to x64 to get a
dll
file ready for Unity project with x64 architecture. (Optional: You could also build x86 version too) -
Create a new Unity project.
-
Copy
dll
file fromTestExportCPPClass/x64/Debug
into Unity'sAssets/Plugins/x86_64
directory. -
Open Unity project and copy the C# script from
TestImportCPPClass/Assets/
directory. -
Create an empty GameObject in the scene and attach the script to it.
-
Press Play button to see the output in the console.