python - 如何将单个 PyObject(在 C++ 后端创建)传递给嵌入式 Python 解释器?

标签 python c++ c

您好,我正在编写一个新的 Python 类型,定义如下:

typedef struct 
{
    PyObject_HEAD
    /* Type-specific fields go here. */
    int * value
} Noddy;

我还定义了所需的所有其他方法和属性,如下所述:https://docs.python.org/2/extending/newtypes.html .

问题是我可以在 Python 中创建和使用我的新对象而没有任何问题,但是当我尝试在 C 中创建对象时我无法传输到 Python 解释器。我正在使用 C++ 后端,Python 是嵌入式的,然后被扩展(扩展嵌入式 python)以提供更多的脚本功能。

重点是当我创建 PyObject 时:

PyObject * pNoddy;
// Create Object
pNoddy= _PyObject_New(&pynoddy_PyNoddyType);
// Initialize Object.
pNoddy= PyObject_Init(pNoddy, &pynoddy_PyNoddyType);

现在在 pNoddy 上,我有一个之前定义的类型的 PyObject。我想将它加载到我的 Python 解释器上。为此,我尝试了以下代码,但它崩溃了。

PyObject *pValue, *pFunc;
// ("addNoddy") is a function defined in Python.
pFunc = PyString_FromString("addNoddy");
// VM is the main module of my system. pNoddy is the PyObject.
pValue = PyObject_CallMethodObjArgs(VM, pFunc, pNoddy);
/********************* NEVER REACH THIS POINT **********************/
Py_DECREF(pValue);

最佳答案

你需要像这样调用 PyObject_CallMethodObjArgs

pValue = PyObject_CallMethodObjArgs(VM, pFunc, pNoddy, NULL);

来自文档:

PyObject* PyObject_CallMethodObjArgs(PyObject *o, PyObject *name, ...,NULL)

Return value: New reference. Calls a method of the object o, where the name of the method is given as a Python string object in name. It is called with a variable number of PyObject* arguments. The arguments are provided as a variable number of parameters followed by NULL. Returns the result of the call on success, or NULL on failure.

关于python - 如何将单个 PyObject(在 C++ 后端创建)传递给嵌入式 Python 解释器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23627299/

相关文章:

c++ - 使用 Howard Hinnant 的库解析带有时区名称的日期/时间时出现问题

python - 套接字超时无法正常工作的Python

Python BigQuery 脚本 bigquery.jobs.create 错误

c++ - 如何使用模板 extern 关键字分隔测试类型?

c++ - 一个类通过多个类应该如何完成?

c - 每个线程组的 Pthread 互斥量

python - Python 编码问题

python - Flash 消息未出现在 flask 中

c++ - x64 CPU 上的原子 16 字节读取

c - 什么时候可以将整数传递给需要无符号的函数,反之亦然