How to use a C++ module from a Mono app
-
05-07-2019 - |
Question
I'm trying to run my C#/C++ app on Linux after developing it on Windows.
A small part of it, FooLib, is written in C++ which is pinvoked from C# for performance. FooLib uses no system calls, only standard C++ functionality. It exports a single function, declared as:
extern "C" __declspec(dllexport) void Foo(float*, int, float*);
It's compiled with Visual C++. I tried running the app under mono with the windows-compiled FooLib.dll, but the dll loading (DllImport) failed with:
Unhandled Exception: System.DllNotFoundException:Foo(single[2],int,single[])
So, what should I do?
- Change the exporting declaration in some way?
- Compile the thing into a .so library with gcc on Linux, then load that?
- Crosscompile it into a .dll with gcc on Linux, then load that?
- Something else?
Solution
You need to recompile your library on Linux, you will get a foolib.so. Then you have to create a DllMap (check this link) so that you don't have to specify a *.so library name for Linux in your C# code and a separate *.dll for Windows - that's just a way to conveniently map the library name depending on the OS.
OTHER TIPS
A very cool tool for automating native bindings is SWIG. http://www.swig.org/
Agree with the 1st comment. Your .NET code should run fine on Linux without any recompile, but your native invocation needs to be natively compiled.