4

I just have a question about running a python object in C++. Let me explain what I want to do in the following example.

int main () {
    // as you know, the python object has its member variables etc, and 
    // I want it to be initialized only once
    py = python_object();   
    while (1) {
        // here, I am hoping to call a member function from the object continously
        // and get a return value. 
        int abc = py.get_num(); 
        if (abc < 0) break;
        do_something_in_my_cpp_code();
    }


}

The python object that I was talking about this here Capture oOjbect.

I am wondering how difficult would this be, if you guys have any experience of dealing with things like this. I am also open to other possible methods, such as the reverse (running a C++ object inside a python script).Thanks!

user3222184
  • 1,071
  • 2
  • 11
  • 28
  • Of course it is *possible*. The *real* question is how much effort it will take.. – Jesper Juhl Aug 08 '17 at 20:13
  • Yes, this is what I am asking really. I am wondering how difficult would that be? – user3222184 Aug 08 '17 at 20:14
  • 1
    Then why didn't you ask *that* question? The obvious response to "is it possible" is "yes" - and then we move on. Ask the *real* question. – Jesper Juhl Aug 08 '17 at 20:18
  • As a comment: the reverse way is easy using SWIG. (Calling C++ Objects from Python). That way you are also using the power of both languages correctly. What you are planning is prob possible but much harder. – lalala Aug 08 '17 at 20:19
  • @lalala, the reverse way also works for me. I am wondering how difficult would that be? – user3222184 Aug 08 '17 at 20:20
  • @JesperJuhl, let me re-frame my question, sorry about that – user3222184 Aug 08 '17 at 20:21
  • You should read https://stackoverflow.com/questions/16962430/calling-python-script-from-c-and-using-its-output#16963206 – R2RT Aug 09 '17 at 07:04
  • Not difficult. Check out this here: http://realmike.org/blog/2010/07/18/python-extensions-in-cpp-using-swig/ – lalala Aug 09 '17 at 08:26

1 Answers1

0

solution 1 create a small python script that calls your function and prints the result. then , in the c++ program use popen to call the python script and retrieve the displayed value.

solution 2 embed python in your c++ program https://docs.python.org/2/extending/embedding.html

if you have only very few python calls, I think solution 1 is the faster and safer way.

sancelot
  • 1,905
  • 12
  • 31