我有一个实现给定功能的 python 类,例如文件 Test_script.py 是:
class Test(object):
def __init__(self,name):
self.name=name
def f1(self,n):
return n**2
def f2(self,n,m):
return n+m
def f3(self,word):
print word
我如何构建一个简单地包装此类和所有函数的 C++ 类,以便该类可以反过来被其他 C++ 类/代码使用? boost::python 是否有助于提供一些快捷方式?
为什么这很重要? 因为可以有具体的用例,在 python 中实现给定功能更快更容易,因为可以重用许多经过良好测试和记录的模块(例如解析、numpy 函数等),而不是从头开始在 C++ 中。上面的类是一个玩具问题,一旦清楚如何将其包装/嵌入到 C++ 中,处理更复杂的功能就会很容易。
谢谢
最佳答案
您是否查阅过有关在 C++ 应用程序中嵌入 Python 功能的文档?注意 Boost.Python 接口(interface),尤其是 Python Interpreter C API。 (Boost.Python 更专注于用 C++ 编写 Python 扩展,而不是相反。)
供引用:
- http://docs.python.org/2/extending/embedding.html
- http://docs.python.org/2/c-api/index.html
- http://docs.python.org/2/c-api/concrete.html
- http://www.boost.org/doc/libs/1_55_0b1/libs/python/doc/tutorial/doc/html/python/embedding.html
也可以在这里查看我的答案,了解 C API 的简单应用(从 C 应用程序使用 matplotlib):
这是另一个简单示例,说明如何使用 C API 导入 Python 模块并从 C++ 应用程序中执行它们的功能。有关详细信息,请参阅文档。
#include <Python.h>
#include <boost/algorithm/string/join.hpp>
#include <vector>
#include <string>
#include <iostream>
int main(int argc, const char** argv) {
// get data to hash
if (argc < 2) {
std::cout << "please add some command line args\n";
return -1;
}
std::string data = boost::algorithm::join(
std::vector<std::string>(argv+1, argv+argc), " ");
std::cout << "compute md5 of string: '" << data << "'\n";
// initialize Python API
Py_Initialize();
// import hashlib module
PyObject *pHashlib = PyImport_ImportModule("hashlib");
// get hash function
PyObject *pHashlibMd5 = PyObject_GetAttrString(pHashlib, "md5");
// build function argument tuple
PyObject *pFuncParams = PyTuple_New(1);
PyTuple_SetItem(pFuncParams, 0, PyString_FromString(data.c_str()));
// call function
PyObject *pMd5 = PyObject_CallObject(pHashlibMd5, pFuncParams);
// get function to retrieve hex digest
PyObject *pMd5Hexdigest = PyObject_GetAttrString(pMd5, "hexdigest");
// call function
PyObject *pRet = PyObject_CallObject(pMd5Hexdigest, 0);
// print result
std::cout << PyString_AsString(pRet) << "\n";
// deinitialize
Py_DECREF(pRet);
Py_DECREF(pMd5Hexdigest);
Py_DECREF(pMd5);
Py_DECREF(pFuncParams);
Py_DECREF(pHashlibMd5);
Py_DECREF(pHashlib);
Py_Finalize();
}
构建并运行:
$ g++ test.cc -I /usr/include/python2.7 -l python2.7
$ ./a.out Hello World
compute md5 of string: 'Hello World'
b10a8db164e0754105b7a99be72e3fe5
比较:
>>> import hashlib
>>> print hashlib.md5('Hello World').hexdigest()
b10a8db164e0754105b7a99be72e3fe5
希望这对您有所帮助。
关于c++ - 如何将 python 类包装到 C++ 类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20643423/