![](/img/trans.png)
[英]How can I use PyObject_IsInstance with a non-builtin class as second argument?
[英]Why PyObject_IsInstance always return 0 in my sample code
我编写了一个示例来学习python,但是当调用PyObject_IsInstance时,此函数始终返回0。这是我的c代码ReadBuf.c
#include "Python.h"
static PyObject* Test_IsInstance(PyObject* self, PyObject* args){
PyObject* pyTest = NULL;
PyObject* pName = NULL;
PyObject* moduleDict = NULL;
PyObject* className = NULL;
PyObject* pModule = NULL;
pName = PyString_FromString("client");
pModule = PyImport_Import(pName);
if (!pModule){
printf("can not find client.py\n");
Py_RETURN_NONE;
}
moduleDict = PyModule_GetDict(pModule);
if (!moduleDict){
printf("can not get Dict\n");
Py_RETURN_NONE;
}
className = PyDict_GetItemString(moduleDict, "Test");
if (!className){
printf("can not get className\n");
Py_RETURN_NONE;
}
/*
PyObject* pInsTest = PyInstance_New(className, NULL, NULL);
PyObject_CallMethod(pInsTest, "py_print", "()");
*/
int ok = PyArg_ParseTuple(args, "O", &pyTest);
if (!ok){
printf("parse tuple error!\n");
Py_RETURN_NONE;
}
if (!pyTest){
printf("can not get the instance from python\n");
Py_RETURN_NONE;
}
/*
PyObject_CallMethod(pyTest, "py_print", "()");
*/
if (!PyObject_IsInstance(pyTest, className)){
printf("Not an instance for Test\n");
Py_RETURN_NONE;
}
Py_RETURN_NONE;
}
static PyMethodDef readbuffer[] = {
{"testIns", Test_IsInstance, METH_VARARGS, "test for instance!"},
{NULL, NULL}
};
void initReadBuf(){
PyObject* m;
m = Py_InitModule("ReadBuf", readbuffer);
}
下面是我的python代码client.py
#!/usr/bin/env python
import sys
import ReadBuf as rb
class Test:
def __init__(self):
print "Test class"
def py_print(self):
print "Test py_print"
class pyTest(Test):
def __init__(self):
Test.__init__(self)
print "pyTest class"
def py_print(self):
print "pyTest py_print"
b = pyTest()
rb.testIns(b)
我将b作为pyTest的实例传递给C,并由PyArg_ParseTuple解析为pyTest。 运行PyObject_IsInstance时,结果始终为零,这意味着pyTest不是Test的实例。 我的问题:将参数从python传递到C时,类型是否更改? 如果要比较pyTest是Test的实例怎么办?
谢谢,瓦特尔
当扩展尝试加载client
模块时, client
模块未完全加载。 client
执行两次(请仔细观察输出)。
所以Test
中client.py
和Test
扩展模块中引用不同的对象。
您可以通过在单独的模块中提取类来解决此问题。 (说common.py
),并在client.py
和扩展模块中导入common
。
观看演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.