Quick Start¶
This page is a quick guide to set up a CMake based C++ project and call mathematica functions. It is recomended to check the Build Instructions before going through this page. At the end of the Build Instructions we built a very simple Hallo World project using mathematica++. Here we continue from the end of that page.
However if you want an one liner to experiment you can run the following script to set up an example Hallo World project.
$ bash <(curl -s https://gitlab.com/neel.basu/mathematicapp/snippets/1752115/raw)
This script will ask for a project name and it will create a CMake project in that PROJECT_NAME directory. Inside that mathematica++ library will be pulled from gitlab. A main.cpp will be created with some small example. You can cd to PROJECT_NAME/build directory and run make to compile. Please note that you must have cmake, mathematica, boost installed in order it to work.
Calling Mathematica Function from C++¶
In order to call a function we need to tell! C++ that such name exists. MATHEMATICA_DECLARE(Func) does that job. After that declaration we can use Func as a regilar C++ function. In the example below we declare the function Divisors. Invoking a mathematica function call is done by using << operator on the shell. Once the function has been invoked we need to fetch the result. The operator >> is used to fetch a mathematica output. Then we cast the value to a compatiable stl type.
#include <iostream> #include <mathematica++/mathematica++.h> using namespace mathematica; MATHEMATICA_DECLARE(Divisors) int main(){ connector shell; if(!shell.connected()){ std::cout << "Failed to connect to Mathematica !!" << std::endl; return 1; } value result; shell << Divisors(1729); shell >> result; std::cout << result << std::endl; typedef std::vector<int> divisors_type; divisors_type divisors; divisors = cast<divisors_type>(result); for(int n: divisors){ std::cout << n << std::endl; } return 0; }
The connector constructor establishes the connection to mathematica using the default platform specific argumements. However if you need to connect using a different arguments we may use the overloaded constructors that takes (argc, argv) as its input.
mathenatica++/declares.h declares several mathematica functions. As mathematica++.h includes that header you may not need to MATHEMATICA_DECLARE for some functions e.g. FactorInteger
In the next example we incorporate a symbol an option to the mathematica function FindRoot. The equivalent mathematica syntax for the next example is
Values[FindRoot[ArcTan[1000 Cos[x]], {x, 1, 2}, Method -> "Newton"]]
And the Equivalent C++ code is very similar to the above. However Note std::string is prefered that character literals.
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