Adam
Adam

Reputation: 905

Embedding python in C++ and extracting c++ types

I'm trying to embed simple python instructions in my c++ program. I'm unable to extract c++ types from the python object types... Would appreciate any help!

Sample Program:

#include <iostream>
#include <Python.h>

using namespace std;

int main()
{
Py_Initialize();
auto pModule = PyImport_ImportModule("math");
auto pFunc = PyObject_GetAttrString(pModule, "sin");
auto pIn = Py_BuildValue("(f)", 2.);
auto pRes = PyObject_CallObject(pFunc, pIn);

auto cRes = ???;    

cout << cRes << endl;
Py_Finalize();
}

The program should simply print the result for sin(2).

Upvotes: 0

Views: 52

Answers (1)

Zrax
Zrax

Reputation: 1670

You'll want to know what type(s) to expect from the function call, including errors... If the function raised an exception, the PyObject_CallObject should return NULL, so check for that first:

if (!pRes) {
    PyErr_Print();
    // don't do anything else with pRes
}

Otherwise, you can check for and interpret each type you might expect from the Python function call:

if (pRes == Py_None) {
    cout << "result is None" << endl;
} else if (PyFloat_Check(pRes)) {
    auto cRes = PyFloat_AsDouble(pRes);
    cout << cRes << endl;
} else if (<other checks>) {
    // Handle other types
} else {
    cout << "Unexpected return type" << endl;
}

In the case of your math.sin() call, you can probably safely assume either an exception or a PyFloat return.

Upvotes: 1

Related Questions