I'm trying to load a C++ function compiled to a shared library from Mathematica 8.0. I did manage to use a C function using MathLink but MathLink does not seem to support C++ functions. So I tried to create a shared library and load it through LibraryLink, but LibraryFunctionLoad does not seem to be able to load a C++ function. Does anyone managed to use a C++ function within Mathematica, and if so, what are the tricks that one have to do to make it work?
The problem is that the C++
code uses mangling of the symbols being exported.
This encodes the namespace, classname, return type, name and parameters as part of the exported symbol. This means that a function called:
int hello(int x, int y, int z)
exports as something like:
_Z5helloiii
This was done on g++ on linux, windows has a different mangling scheme.
In order to ensure that functions are exported in a C compatible way, you wrap the function in the extern "C"
mechanism, which causes it to be exported in a form that is compatible with MathLink
so you use the following in the header:
#ifdef __cplusplus
extern "C" {
#endif
int hello(int x, int y, int z);
#ifdef __cplusplus
}
#endif
As long as you #include
this header in your C++
implementation, it should link correctly with MathLink