那么,这两件事都有办法吗?从C++调用python函数,调用Python C++函数?
这是我的C++代码< /p>
#include <Python.h>
#include <boost/python.hpp>
using namespace boost::python;
// <----------I want to use this struct in my python file---------
struct World
{
void set(std::string msg) { this->msg = msg; }
std::string greet() { return msg; }
std::string msg;
};
// Exposing the function like its explained in the boost.python manual
// but this needs to be compiled to a .so to be read from the multiply.py
BOOST_PYTHON_MODULE(hello)
{
class_<World>("World")
.def("greet", &World::greet)
.def("set", &World::set)
;
}
// <---------------------------------------------------------------
int
main(int argc, char *argv[]) // in the main function is only code for embedding the python file, its not relevant to this question
{
setenv("PYTHONPATH",".",1);
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
int i;
if (argc < 3) {
fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
return 1;
}
Py_Initialize();
pName = PyString_FromString(argv[1]);
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(argc - 3);
for (i = 0; i < argc - 3; ++i) {
pValue = PyInt_FromLong(atoi(argv[i + 3]));
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
return 1;
}
/* pValue reference stolen here: */
PyTuple_SetItem(pArgs, i, pValue);
}
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
printf("Result of call: %ld\n", PyInt_AsLong(pValue));
Py_DECREF(pValue);
}
else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr,"Call failed\n");
return 1;
}
}
else {
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else {
PyErr_Print();
fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
return 1;
}
Py_Finalize();
return 0;
}
这是我的Python文件
import hello_ext #importing the C++ file works only if its compiled as a .so
planet = hello.World() #this class should be exposed to python
planet.set('foo')
def multiply(a,b):
planet.greet()
print "Will compute", a, "times", b
c = 0
for i in range(0, a):
c = c + b
return c
简而言之,与嵌入式Python静态链接的Python扩展需要在初始化解释器之前将其模块初始值设定项函数显式地添加到初始化表中。
Python使用^{} 宏来定义Python模块初始化器。结果函数不是模块导入器。这种区别类似于创建
example.py
模块并调用import example
。导入模块时,Python将首先检查模块是否是内置模块。如果模块不在那里,那么Python将搜索module search path试图根据模块名查找Python文件或库。如果找到库,那么Python希望库提供一个函数来初始化模块。一旦找到,导入将在modules表中创建一个空模块,然后对其进行初始化。对于静态链接的模块,例如原始代码中的
hello
,模块搜索路径将没有帮助,因为没有库供其查找。对于嵌入,module table and initialization function文档声明,对于静态模块,除非在初始化表中有一个条目,否则不会自动调用模块初始值设定项函数。对于Python 2和Python 3,可以通过在^{} 之前调用^{} 来实现这一点:
还要注意,Python的C API用于在Python 2和3之间嵌入更改的模块初始化函数的命名约定,因此对于
BOOST_PYTHON_MODULE(hello)
,可能需要对python2使用&inithello
,对Python 3使用&PyInit_hello
。下面是一个完整的例子demonstrating让一个嵌入式Python导入一个
demo
用户模块,然后导入一个静态链接的hello
模块。它还调用用户模块demo.multiply
中的函数,然后调用通过静态链接模块公开的方法。demo.py
的内容:用法:
在上面的代码中,我选择使用Boosi.Python代替Python /C API,C++注释用等效的Python代码注释。我发现它更简洁,更不容易出错。如果发生Python错误,Boost.Python将抛出一个异常,所有引用计数都将得到适当处理。
另外,在使用Boost.Python时,不要调用^{} 。根据Embedding - Getting started部分:
相关问题 更多 >
编程相关推荐