Update: While at the time of writing the question loading DLLs with .NET/Link seemed easier, now I always use LibraryLink, which I recommend to anyone with a similar problem!
As of Mathematica 8, what is the minimal effort way to integrate an existing C++ function into Mathematica?
I think we have these:
- MathLink (it was quite long ago I used it last time)
- communication through pipes/files (
Import
is slow,ReadList
not so much) - LibraryLink (??)
Mathematica 8's C code generation features (??)(apparently this is not relevant)
The keyword here is minimal effort. Which is the most convenient way, including the learning curve for the particular method?
I'm mainly interested in doing it on Windows. My particular function computes a long list of real numbers. The function input consists only of a few scalars (int
& double
).
An answer of the type "You'll likely spend the least time if you use technology X" is useful. A concrete example of how to do it using a small function is even better.
Answers
Each and every answer I got is great, and each demonstrates a different technology. It's impossible to choose a definitive one. Here's a small "table of contents" for them:
- MathLink
- Read result from pipes, pass arguments on command line to separate process
- LibraryLink
- Using .NETLink for loading functions from arbitrary DLLs
A presentation about the topic from the Wolfram Technology Conference is here (CDF file).
Experiences
I used two of these methods: the .NETLink method and Library Link. These are my personal experiences:
.NETLink This was easy to set up, however, I'd recommend it only for when you already have a compiled DLL from which you need to load functions (e.g. do something like this). If you compile your own DLL: once the DLL is loaded, it is locked and cannot be overwritten. A quick and dirty way to allow overwriting it is realoding NETLink with
ReinstallNET[]
.Advantages: Very quick and easy, only Mathematica code is needed if the functions are already compiled into a DLL.
Disadvantages: Windows-only, does not parallelize from within Mathematica, and the calculation will not be interruptible.
Library Link It's much easier to use this than what it looks like at first. Less setup is needed than in the case of MathLink, and compilation is automated from within Mathematica.
Advantages: Also quite easy, but both Mathematica and C code are needed. It is parallelizable, and easily made interruptible. The library can be unloaded (for recompilation) using
LibraryUnload
.
List
of scalars, or a finite number of parameters? $\endgroup$CCompilerDriver/tutorial/Compilation#472267182
in the Mathematica documentation is probably a good starting point. $\endgroup$