Message Boards Message Boards


Call Mathematica functions from C++

Posted 3 years ago
2 Replies
11 Total Likes

Here is an example of how researchers from CERN use Mathematica functions in C++.

I have tried to dissect the code, but I still get plenty of errors when I try to compile it.

Can anyone show a simple example of how to efficiently call Mathematica functions from C++?

2 Replies

There are several possible ways discussed in detail here:

There are more LibraryLink examples here:

Once you are familiar with LibraryLink, you might want to take a look at my package, LTemplate, which makes it much quicker to build complex LibraryLink applications:

This is a 2 years old post. But I think It wouldn't harm linking another post here.

I have recently posted about a C++ library mathematica++ in the forum that I have been working on for long days. mathematica++ is a C++ library that uses WSTP and template magic so that user code can have more mathematica like syntax. Have a look at this post

An example code using mathematica++ looks like the following

value result;
typedef std::vector<std::vector<int>> ivv_type;
shell << FactorInteger(2434500); // << Invoke mathematica function FactorInteger
shell >> result; // << Fetch result
ivv_type prime_powers = mathematica::cast<ivv_type>(result); // << Cast to STL
for(auto pp: prime_powers){
    std::cout << pp[0] << " ^ " << pp[1] << std::endl;
// Prints the following output
// 2 ^ 2
// 3 ^ 2
// 5 ^ 3
// 541 ^ 1

Mathematica Expressions can be built and stored in C++

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
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract