2

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 を実行すると、結果は常に 0 になります。これは、pyTest が Test のインスタンスではないことを意味します。私の質問: Python から C にパラメーターを渡す場合、型は変更されますか? pyTest が Test のインスタンスである場合、それを比較したい場合はどうすればよいですか?

ありがとう、ヴァテル

4

1 に答える 1

1

拡張機能がモジュールをロードしようとしたときに、clientモジュールが完全にロードされていませんclient。; の実行clientが 2 回発生します (出力を注意深く見てください)。

そのTestため、inclient.pyTestin 拡張モジュールは異なるオブジェクトを参照しています。

別のモジュールでクラスを抽出することで、これを回避できます。(Say )と拡張モジュールの両方にcommon.pyインポートします。commonclient.py

デモをご覧ください。

于 2014-02-19T08:09:49.880 に答える