简体   繁体   English

如何使用本机Python / C API从C ++创建python自定义类型?

[英]How can I create python custom types from C++ using native Python/C API?

Explanation is defined below: 解释定义如下:

I have defined a new Python type named "Ex1". 我定义了一个新的Python类型,名为“ Ex1”。

typedef struct {
    PyObject_HEAD
    PyObject * int_id;
    int * value;

} Ex1;

With this type in mind and all appropriate methods generated and validated in Python interpreted (it works pretty well). 考虑到这种类型,并使用Python解释生成并验证的所有适当方法(效果很好)。 I want to be able to create a python object of the new Ex1 Type from C++ backend. 我希望能够从C ++后端创建新的Ex1类型的python对象。 A typical structure of what I need is: 我需要的典型结构是:

int main 
{
     // Create Ex1 Object.
     Ex1 Example;

     // Call PythonC-API method to include Ex1 Object into the python interpreter.
     // ¿Any function-method from Python API to perform this task?
}

Actually I managed to solve this problem using python docs: 实际上我设法使用python docs解决了这个问题:

https://docs.python.org/2/extending/newtypes.html https://docs.python.org/2/extending/newtypes.html

First of all it is necessary to define the appropiate methos as is described in the python docs ( 1 ) . 首先,有必要定义适当的方法,如python docs( 1 )中所述。 Assuming the PyType created has two attributes (varp1 and varp2): 假设创建的PyType具有两个属性(varp1和varp2):

PyObject * create_Ex1(vartype1 var1, vartype2 var2)
{
    PyObject * pInst = PyObject_CallObject((PyObject *)&Ex1Type, NULL);
    ((Ex1*)pInst)->varp1 = var1;
    ((Ex1*)pInst)->varp2 = var2;    
    return pInst;
}

and

static int Ex1_init(Ex1 *self, PyObject *args, PyObject *kwds)
{   
    // On init return -1 if error
    self->varp1= NULL;
    self->varp2= NULL;
    return 0;
};

This is defined on the static PyTypeObject Ex1Type as is described in the python docs ( 1 ). 如python docs( 1 )中所述,这是在静态PyTypeObject Ex1Type上定义的。

Then the object is created and initialized using this line: 然后使用此行创建和初始化对象:

PyObject* Ex1_obj = create_Ex1(var1, var2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM