4

Introduction

I'm trying to do a simple thing - in theory, but so far not in practise. I have C++ console application, with embedded python script. It has to pass some variables inside python, do calculation, and send it back.

Example code

my cpp file look like this (based on THIS answer):

#include <iostream>
#include <boost/python.hpp>

using namespace boost::python;

int main()
{
    int a = 2;
    int b = 3;

    Py_Initialize();
    try
    {
        object module = import("__main__");
        object name_space = module.attr("__dict__");
        exec_file("Script.py", name_space, name_space);

        object MyFunc = name_space["MyFunc"];
        object result = MyFunc(a,b);

        int sum = extract<int>(result["sum"]);
        std::cout << sum;
    }
    catch (error_already_set)
    {
        PyErr_Print();
    }

    Py_Finalize();
}

My Script.py file is very simple

def MyFunc(a,b):
    result = a+b
    return result

The Issue

I expected, that python will accept two variables, sum it, and let extract it back do my C++. Then C++ print the results. However it ends with following error:

TypeError: 'int' object has no attribute '__getitem__'

I think that MyFunc(a,b) is not correct call, however I can't figure why. Should I pass variables in other way? If yes, pleas explain me how to do this.

2
  • 2
    I think, you need extract<int>(result). Commented Feb 25, 2019 at 18:54
  • Indeed, it works. It seems that I overgeneralized the code I referenced above. It's really surprising, the mistake was so elemental. Commented Feb 25, 2019 at 19:05

0

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.