[C++-sig] libboost-python: how to create module in C++-runtime and use it from python code, in python 3.x
Nikolay Shaplov
dhyan at nataraj.su
Sat Jul 23 03:06:17 EDT 2022
В письме от пятница, 22 июля 2022 г. 10:39:09 MSK пользователь Nikolay Shaplov
написал:
I finally managed to fix it.
Key point here was, that in python3.x you should manually add such modules to
inittab(whatever it is) using PyImport_AppendInittab
Finally my sample that builds with both 2.7 anx 3.x pythons looks like this
#include <boost/python.hpp>
std::string provide_hello() {
return "hello world provided";
}
BOOST_PYTHON_MODULE(_hello_provider) {
using namespace boost::python;
def("provide_hello", &provide_hello);
}
int main()
{
#if PY_MAJOR_VERSION >= 3
PyImport_AppendInittab((char*)"_hello_provider", PyInit__hello_provider);
#else
PyImport_AppendInittab((char*)"_hello_provider", init_hello_provider);
#endif
Py_InitializeEx(0);
try {
boost::python::object modImp = boost::python::import("imp");
PyImport_AddModule("test_module");
modImp.attr("load_source")("test_module", "test_module.py");
boost::python::exec("print(test_var)",
boost::python::import("test_module").attr("__dict__"));
boost::python::exec("print(hello_static())",
boost::python::import("test_module").attr("__dict__"));
boost::python::exec("print(hello_provided())",
boost::python::import("test_module").attr("__dict__"));
}
catch (const boost::python::error_already_set&)
{
PyErr_Print();
}
Py_Finalize();
}
Special thanks to https://github.com/TNG/boost-python-examples/tree/main/10-Embedding authors and O02eg from linux.org.ru
--
Nikolay Shaplov aka Nataraj
Fuzzing Engineer at Postgres Professional
Matrix IM: @dhyan:nataraj.su
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 488 bytes
Desc: This is a digitally signed message part.
URL: <https://mail.python.org/pipermail/cplusplus-sig/attachments/20220723/3b528ada/attachment.sig>
More information about the Cplusplus-sig
mailing list