您好,我正在编写一个新的 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/