C扩展python中的类实例变量

时间:2018-03-06 02:50:05

标签: python

我有一个python模块来执行矩阵操作,并希望使用Python / C api在C中将其编码为C python模块。我正在使用一个名为Matrix的类,我想继续使用类模型。我可以初始化类,但无法弄清楚如何使用像python self.var中的实例变量。我试过看文档并尝试寻找示例,但我找不到任何帮助。

matrix.c

struct matrixStruct {
    int rows;
    int cols;
    float **matrix;
};

static PyObject * Matrix_init(PyObject *self, PyObject *args) {

    int cols, rows;
    PyObject *selfv;
    struct matrixStruct m;
    Py_INCREF(Py_None);

    // __init__ takes two args, rows, cols
    if (!PyArg_ParseTuple(args,"Oii",&selfv,&rows,&cols)){
        perror("ParseTuples");
        return NULL;
    }
    m.rows = rows;
    m.cols = cols;

    // Create the matrix
    m.matrix = malloc(m.rows*sizeof(float *));
    if (m.matrix == NULL) {
        return NULL;
    }
    for (int i = 0; i < m.rows; i++) {
        m.matrix[i] = malloc(m.cols*sizeof(float));
        if (m.matrix[i] == NULL) {
            return NULL;
        }
    }

    //init the matrix with all 0
    for (int i = 0; i < m.rows; i++) {
        for (int j = 0; j < m.cols; j++) {
            m.matrix[i][j] = 0;
        }
    }

    return Py_None;
}

static PyMethodDef ModuleMethods[] = { {0, 0} };

PyMODINIT_FUNC initMatrix(void) {

    PyMethodDef *def;

    PyObject *module = Py_InitModule("Matrix", ModuleMethods);
    PyObject *moduleDict = PyModule_GetDict(module);
    PyObject *classDict = PyDict_New(  );
    PyObject *className = PyString_FromString("Matrix");
    PyObject *matrixClass = PyClass_New(NULL, classDict, className);
    PyDict_SetItemString(moduleDict, "Matrix", matrixClass);
    Py_DECREF(classDict);
    Py_DECREF(className);
    Py_DECREF(matrixClass);

    for (def = MatrixMethods; def->ml_name != NULL; def++) {
        PyObject *func = PyCFunction_New(def, NULL);
        PyObject *method = PyMethod_New(func, NULL, matrixClass);
        PyDict_SetItemString(classDict, def->ml_name, method);
        Py_DECREF(func);
        Py_DECREF(method);
    }

}

0 个答案:

没有答案