我写了一个示例来学习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)
我将作为 pyTest 实例的 b 传递给 C,并由 PyArg_ParseTuple 解析给 pyTest。运行 PyObject_IsInstance 时,结果始终为零,这意味着 pyTest 不是 Test 的实例。我的问题:当从 python 向 C 传递参数时,类型是否改变了?如果我想比较 pyTest 是 Test 的一个实例,我应该怎么做?
谢谢, 瓦特尔