Message Boards Message Boards

Call Mathematica functions from C++

Posted 8 years ago

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++?

POSTED BY: Sandu Ursu
2 Replies

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 http://community.wolfram.com/groups/-/m/t/1419096

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
POSTED BY: Neel Basu

There are several possible ways discussed in detail here:

http://mathematica.stackexchange.com/questions/8438/minimal-effort-method-for-integrating-c-functions-into-mathematica

There are more LibraryLink examples here:

http://community.wolfram.com/groups/-/m/t/189735/

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:

http://mathematica.stackexchange.com/questions/96127/how-to-simplify-writing-librarylink-code

POSTED BY: Szabolcs Horvát
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract