Coupling c++/python cantera api's via pybind11

65 views
Skip to first unread message

ajp

unread,
Feb 18, 2019, 12:53:36 PM2/18/19
to Cantera Users' Group
Hi,

I thought I'd ask on the off chance that somebody has tried this. My basic work flow is a c++ solver that I'd like to have operate on a MultiPhase object (I think at least I do, I've just asked a question about that too).  However, I'd like python to be used to set up the object for quicker development and user interaction rather than encoding it all in c++.  So I've been trying to use pybind11 to achieve this.  Code so far looks like this:

#include <pybind11/embed.h> // everything needed for embedding
namespace py = pybind11;
//
#include "cantera/thermo.h"
using namespace Cantera;
//
#include <iostream>

int main()
{
    // start the interpreter and keep it alive
    py::scoped_interpreter guard{};
    py::module calc = py::module::import("setup");

    py::object result = calc.attr("example")();
   auto* gas = result.cast<ThermoPhase*>();
   std::cout << gas->report() << std::endl;
}

In the same directory I have setup.py

import cantera as ct

def example():
   gas1 = ct.ThermoPhase('gri30.xml')
   # print gas object
    gas1
()
   return gas1

Calling python from c++ works fine as I hit the print statement in the python code, however, returning the object on the next line (which is crucial for me) fails in the cast on the c++ side.  This is basically a pybind11 question, but I thought I'd ask here first in case somebody has tried this.  I appreciate I'm using a ThermoPhase not a MultiPhase object: this is a minimal working example to that end.

Any help appreciated.
Andy

Ray Speth

unread,
Feb 18, 2019, 3:34:42 PM2/18/19
to Cantera Users' Group

Andy,

This is an interesting idea — I haven’t seen any attempts to work with Cantera Python objects in C++ before. If there’s a way to get this working, it’s going to be somewhat more complex than what you’re trying now. The Python (Cython) ThermoPhase object is not just a C++ ThermoPhase*, but it does hold a pointer to the C++ object. I don’t know how pybind11 works, but presumably you need to be able to tell how to get to that pointer. It’s stored as the thermo member of the underlying _SolutionBase class, as you can see in _cantera.pyx, which contains the declarations for all of the Cython extension types.

Regards,
Ray

Kyle Schau

unread,
Jul 11, 2021, 4:04:56 PM7/11/21
to Cantera Users' Group
Hey Ray,

Is the pointer accessible from the python API? I.e. from a gas=ct.Solution("somefile.cti") creation?

thanks,
kyle

Reply all
Reply to author
Forward
0 new messages