My goal is to get a toy C++ library wrapped using SWIG, and accessible to C# / Mono scripts in Unity. (In other words, have the library functionality working in a Windows build of the game. I'll tackle Android next :)
I have been following a combination of Build a C# module (SWIG tutorial), Unity and DLLs (Eric Eastwood) and Getting started with SWiG for Visual Studio projects (Technical Recipes). I have generated two DLLs in Visual Studio 2013 and added them to the Unity project. But accessing the toy method at runtime is failing.
Steps I followed (including common fixes for the error I am receiving):
Create C++ project / custom build
Create C# project
using System;
using System.Runtime.InteropServices;
namespace CSharpExampleLib {
...
}
Build two Release DLLs
CorFlags
to force the C# DLL to be 32-bit (reference) (this does not work / does not apply to C++ DLL) Add DLLs to Unity project
using System.Runtime.InteropServices;
using System.IO;
Invoke method from DLL
Finally, I added a logging call from the simple script to the C# DLL (Intellisense confirms that the DLL and method are accessible):
Debug.Log(CSharpExampleLib.example.fact(3));
// should log the result of 3 factorial
Runtime error
However, when I start the game from the Unity editor, I get the following error:
DllNotFoundException: example
CSharpExampleLib.examplePINVOKE+SWIGExceptionHelper..cctor ()
Rethrow as TypeInitializationException: An exception was thrown by the type initializer for SWIGExceptionHelper
CSharpExampleLib.examplePINVOKE..cctor ()
Rethrow as TypeInitializationException: An exception was thrown by the type initializer for CSharpExampleLib.examplePINVOKE
CSharpExampleLib.example.fact (Int32 n)
SimpleController.Start () (at Assets/scripts/SimpleController.cs:10)
I made several attempts to correct common causes for this error (build as Release, build as 32-bit, check Dependency Walker, etc) to no avail. Is there something SWIG- or Unity-specific I am missing? Any other checks I can perform on my DLLs?
After discussion on the SWIG user mailing list and some careful review, I discovered I was missing two configuration steps:
The C++ DLL must have the same name as the module name specified in the SWIG interface file (so for my toy example using interface file example.i, it is best to name the C++ project "example" and it will generate example.dll)
In the backwards and forwards of resolving other issues, I lost the reference to the autogenerated C++ wrapper (example_wrap.cxx) and needed to re-add it to the C++ project.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.