0

I have an application which will be extensible by Python code but the extensing code will also be using code from the application. Example of what I am trying to achieve:

// wrapped_module.cpp

void api_call()
{
 std::cout << "API call" << std::endl;
}

BOOST_PYTHON_MODULE(API)
{
  boost::python::def("api_call", api_call);
}

// extension.py

import API

def myExtension()
 # ... some python work ... #
 API.api_call()

// application_main.cpp

int main()
{
 // initialize interpreter
 // load "extension.py"
 // make "API" module available for "extension.py", so "import API" works
 // load "myExtension" from "extension.py"
 // myExtension()
 // <see "API call" in console output>

 return 0;
}

"extension.py" will never be called as a standalone script, it will always be loaded by c++ application - therefore I do not need to separately build API.dll module for python to import - or do I?

1

1 Answer 1

1
+300

This is possible but not entirely straightforward.

You need to use an undocumented generated function name, in your case initAPI (it is composed from the word init and your module name, case-sensitive). You need to pass this function as an argument to PyImport_AppendInittab before calling Py_Initialize.

Update In Python 3, use PyInit_API instead if initAPI.

Below is a full working program that embeds Python and extends it with your module, then runs a simple program that uses your module.

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

void api_call()
{
     std::cout << "API call" << std::endl;
}

BOOST_PYTHON_MODULE(API)
{
      boost::python::def("api_call", api_call);
}

int main (int argc, char* argv[])
{
    // Import your module to embedded Python
    PyImport_AppendInittab("API", &initAPI);

    // Initialise Python
    Py_Initialize();

    // Run Python code
    PyRun_SimpleString("import API\n"
                       "API.api_call()\n");

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

3 Comments

I saw couple examples which used PyImport_AppendInittab("something", &initSomething). I was trying hard to find where that mysterious initSomething() actualy is... you hit it. Thanks
I am trying to run this code, but getting an error saying : In function ‘int main()’: full_flow.cpp:17:34: error: ‘initAPI’ was not declared in this scope PyImport_AppendInittab("API",initAPI); any idea why this should happen ?
@BidishaDas In Python 3 it's called PyInit_API.

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.