将Python属性绑定到C++扩展的C++变量

2024-04-26 03:08:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将C++代码编译成Python的扩展,但我在C++中把值赋值给了一些麻烦,也把它们读入Python。p>

我创建了分配和读取值的方法,如下所示:

import hello

if __name__ == "__main__":

    # GET THE VALUE OF 'a'
    a = hello.get_a()
    print('the value of \'a\' is:',a)   

    # SET A VALUE FOR 'a'
    hello.set_a(5.0)

    # GET THE VALUE OF 'a'
    a = hello.get_a()
    print('the value of \'a\' is:',a)   

这将产生:

the value of 'a' is: 1.0
the value of 'a' is: 5.0
<>我想做的是用一种更简单的方式,像把Python的属性与C++变量的值绑定:

import hello

if __name__ == "__main__":

    # GET THE VALUE OF 'a'
    print('the value of \'a\' is:',hello.a) 

    # SET A VALUE FOR 'a'
    hello.a = 5.0

    # GET THE VALUE OF 'a'
    print('the value of \'a\' is:',hello.a) 

我的包装器的一个示例:

#include <Python.h>

/* EXAMPLE OF A CLASS WITH VALUE */
class example {
    public:
        float a;
        example(float a_init);    
};

example::example(float a_init){
    this->a = a_init;
}

example ex(1.0);

/* METHODS CALLS */
static PyObject* get_a(PyObject *self, PyObject *args);
static PyObject* set_a(PyObject *self, PyObject *args);

static PyMethodDef hello_methods[] = {
        {"get_a", get_a, METH_VARARGS,"numpy function tester",},
        {"set_a", set_a, METH_VARARGS,"numpy function tester",},
        {NULL, NULL, 0, NULL}
};

/* MODULE */
static struct PyModuleDef hello_definition = {
        PyModuleDef_HEAD_INIT,
        "hello",
        "A Python module that prints 'hello world' from C code.",
        -1,
        hello_methods
};

/* INIT MODULE */
PyMODINIT_FUNC PyInit_hello(void) {
    Py_Initialize();
    return PyModule_Create(&hello_definition);
}

// METHODS
static PyObject* get_a(PyObject *self, PyObject *args) {
    /* RETURNING VALUE OF 'a' */
    return Py_BuildValue("f", ex.a);;
}

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

    float value;
    if (!PyArg_ParseTuple(args, "f", &value))
        return NULL;

    /* ASSIGNING VALUE OF 'a' */
    ex.a = value;
    Py_RETURN_NONE;
}

有可能吗


Tags: ofthehellogetisvalueexampleargs