C Style
To Call Mathematica functions from C/C++
you need to use ML_
or WS_
functions. Mathematica is now "replacing" MathLink
with WSTP
. However function names are mostly similar. There are C style WSPutT
functions that are used to send an input of type T
to mathematica. and the output is fetched from mathematica using WSNextPacket
and WSGetT
functions. To use these accessing functions first a link needs to be established WSOpenArgcArgv
. The C language Reference lists the functions that you will need to communicate with mathematica using
C/C++
C++ (with mathematica++)
I was mostly interested to use mathematica from C++. So I developed one C++ library mathematica++
that uses template magic for easier interoperability between C++ and Mathematica. The usage example below is copied from the project page.
symbol x("x");
value res;
std::string method = "Newton";
shell << Values(FindRoot(ArcTan(1000 * Cos(x)), List(x, 1, 2), Rule("Method") = method));
shell >> res;
std::vector<double> results = cast<std::vector<double>>(res);
std::cout << results[0] << std::endl; // Prints 10.9956
With mathematica++
you declare a mathematica function using MATHEMATICA_DECLARE(FunctionName)
and then use the function FunctionName
in C++. Like in the example above FindRoot
is being used to solve the equation. It builds an equivalent chain of WS_
functions on runtime. The template function cast<T>
can be sued to cast mathematica returned results back to C++ STL
types.
symbol i("i"); // declare mathematica symbol i
value result_list; // declare the variable to hold the result
shell << Table(i, List(i, 1, 10)); // In Mathematica Table[i, {i, 1, 10}]
shell >> result_list;
std::cout << result_list << std::endl; // Prints List[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
std::cout << result_list->stringify() << std::endl; // Prints List[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
std::vector<int> list;
list = cast<std::vector<int>>(result_list);
shell.import("/path/to/package.m")
can be used to import a mathematica package.
shell << Import("/path/to/package.m")`
also yields the same as well. Because Import
is also a mathametica function that can be declared using MATHEMATICA_DECLARE
I have tested it only on Linux and Mac platforms, but it should work on windows also. The Project is in Free BSD License.
mathematica++ gitlab repository | website | wiki