创建Python构造函数,参数来自c++, PyObject
Create Python Constructor with parameter from C++, PyObject
我有一个这样的python类A
。
class A:
def __init__(self, name):
self.name = name
def print_lastname(self, lastname):
print(lastname)
我必须像这样调用这段代码。
import B
a = B.A("hello")
a.print_lastname("John")
目前,我需要使用这个A
类从我的c++代码。我已经走到这里了。
Py_Initialize();
string hello = "hello";
PyObject *module, *attr, *arg;
module = PyObject_ImportModule("B"); // import B
attr = PyObject_GetAttrString(module, "A"); // get A from B
arg = PyString_FromString(hello.c_str());
instance = PyInstance_New(attr, arg, NULL); // trying to get instance of A with parameter "hello"
Py_Finalize();
但是我得到错误
异常类型错误:'参数列表必须是元组'在模块'threading'从'/usr/lib64/python2.7/threading.pyc'
如何从c++实现从import
语句到a.print_name("John")
语句?
我将稍微重写一下Python类,以便它同时使用参数和成员变量。
# B.py - test module
class A:
def __init__(self, name):
self.name = name
def print_message(self, message):
print message + ' ' + self.name
至于c++部分,几乎一切看起来都很好。你得到的错误是因为PyInstance_New
的参数应该是一个元组。调用函数或方法有多种方式。下面是使用其中一个的完整示例:
// test.c - test embedding.
void error_abort(void)
{
PyErr_Print();
exit(EXIT_FAILURE);
}
int main(int argc, char* argv[])
{
PyObject* temp, * args, * attr, * instance;
Py_Initialize();
if (!(temp = PyString_FromString("John")))
error_abort();
if (!(args = PyTuple_Pack(1, temp)))
error_abort();
Py_DECREF(temp);
if (!(temp = PyImport_ImportModule("B")))
error_abort();
if (!(attr = PyObject_GetAttrString(temp, "A")))
error_abort();
Py_DECREF(temp);
if (!(instance = PyInstance_New(attr, args, NULL)))
error_abort();
if (!PyObject_CallMethod(instance, "print_message", "s", "Hello"))
error_abort();
Py_DECREF(args);
Py_DECREF(attr);
Py_DECREF(instance);
Py_Finalize();
return 0;
}
更多信息请参见Python纯嵌入。
相关文章:
- 使用提升将数据从 PyObject 复制到浮点数 *
- 在 C++ 中对 PyObject 调用"+="
- 在 cpp 中嵌入 python:如何获取指向 python 函数(而不是 PyObject)的 C 指针?
- 使用C对象指针构建PyObject*
- 为什么PyImport_ImportModule返回引用计数为 3 而不是 1 的 PyObject*
- 如何将 PyObject 转换为 UTF-8 字符串
- 如何返回包含 PyObject* 的 boost::p ython::元组?
- 从C++调用 Python 类方法,如果给定一个初始化的类作为 PyObject
- 如何从C++创建c_void_p PyObject,将其传递给Python并将其检索回C++
- 将新的 PyObject * 从 C++ 返回给 Python 最终会出现段错误
- boost.python向现有的PyObject添加绑定(对于例外处理)
- 在 Python 的 C/C++ 扩展中,返回的 PyObject* 应该具有什么引用计数
- 确定PyObject*是否为Pylong Doublescalarobject(Numpy)
- 如何将Python模块(来自PyObject*)转换并保存为二进制数据,以便以后使用
- C++类成员函数返回PyObject*分段错误
- C++到numpy,然后返回到C++,元组PyObject
- 检查 PyObject 是否为“无”
- 如何将 boost python list 转换为 PyObject
- 调用一些PyObject函数会导致segfault-Boost python
- 如何在Python中处理C++中的PyObject*