Python C++扩展单例模式

3
我想为Python(3.x)编写一个C++扩展,以便我可以使用Raspberry Pi上的特定硬件卡片。虽然我没有编写C和/或C ++的经验,但是通过使用Python网站上的文档,我实际上已经使事情正常运转了。我想要做的是将我的类型设置为Singleton,但是如果init方法返回错误(-1),则对构造函数的第二次调用会导致混乱。如果init没有出现错误,则它按预期工作。
我的代码的重要部分:
static PyObject *
MyType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    static MyType *self = NULL;  /* static to create a Singleton */

    if (self == NULL) {
        self = (MyType *)type->tp_alloc(type, 0);

        self->is_initialized = false;
    }
    else {
        Py_XINCREF(self);
    }

    return (PyObject *)self;
}

static int
MyType_init(MyType *self, PyObject *args, PyObject *kwds)
{
    const char *i2c_addr;

    self->rpi_model = RPI_MODEL_B;
    self->enabled_components = COMPONENTS_ALL_BIT;

    static char *kwlist[] = {"rpi_model", "enabled_components", NULL};

    if (self != NULL && !self->is_initialized) {
        if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii", kwlist, &self->rpi_model, &self->enabled_components)) {

            return -1;
        }
    }

    /*
        DO SOME INITIALIZATION STUFF
    */

    if (!self->component_A->testConnection()) {
        PyErr_SetString(InitializationException, "Unable to communicate with component_A.");
        return -1;
    }

    self->is_initialized = true;
    return 0;
}

我还在tp_dealloc成员中安装了以下函数:

static void
MyType_dealloc(PyObject *self)
{
    Py_TYPE(self)->tp_free((PyObject*)self);
}

我在这些方法中添加了一些打印语句(用于调试),似乎在第二次调用MyType_new时,self!= NULL,尽管在初始化失败时已执行MyType_dealloc方法。

是否有人能指点我正确的方向?

1个回答

0

看起来你的MyType_dealloc没有将self设置回NULL

另外,你不需要同时拥有__new____init__ -- 只需将它们全部放在__new__中即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接