0

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).

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.