How to embed Python within C++ and call each other with PyBind11

568 Views Asked by At

I want to embed a Python interpreter within my C++ application, and make them call each other. I followed the sample in the official doc of pybind11, and now I can call a python sub-program and create a object of python's class in the main program of c++, But my python class need to derive from a c++ base class.

Although there is a official sample about deriving a c++ base class within python, but it is extending python with a c++ module(in form of *.so file), not embedding a python interpreter into a c++ application.

There will NOT a shared library(*.so) file in my projects, if I import myCppModule in python, where would it find the module? How should I offer the module in C++?

If I blindly make a *.so file as a module for python, may I encounter a linking conflict? Because there will be two binary code copies of my base class, one copy resides in main executable, and the other reside in the shared library.

Sorry for my ugly English.

1

There are 1 best solutions below

0
On

According to @unddoch 's directive, I found that if we use PYBIND11_EMBEDDED_MODULE macro instead of using PYBIND11_MODULE, we can directly export a module for python in our c++ main executable without exporting a shared library file. Maybe this can help others so I write it down here.