Question

I write a sample to learn python, but when call PyObject_IsInstance, this function always return 0. Here's my c code 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);
}

And below is my python code 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)

I pass b which is an instance of pyTest to C, and it is parsed by PyArg_ParseTuple to pyTest. When run PyObject_IsInstance, the result is always zero, which means pyTest is not a instance of Test. My question: When pass parameter from python to C, is the type changed? How should I do if I want to compare that if pyTest is an instance of Test?

Thanks, Vatel

Was it helpful?

Solution

The client module is not completely loaded when the extension try to load the client module.; Execution of client is occurred twice (Watch the output carefully).

So Test in client.py and Test in the extension module are referencing different objects.

You can workaround this by extracting classes in a separated module. (Say common.py) And import common in both client.py and extension module.

See a demo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top