避免C编写的Python库的垃圾收集

时间:2017-01-18 10:59:04

标签: python c python-c-api

我正在努力学习我的C语言编写的Python库。该代码用于在cp210x中写入寄存器以控制中继卡。代码可以工作,但是Python以某种方式清除了对象。

换句话说,在结束函数后,C变量ttyPort被清除。

这是C代码:

#include <Python.h>
#include <fcntl.h>
#include <stropts.h>

// C variable that holds the tty address (e.g. /dev/ttyUSB0)
const char* ttyPort;

int setRelay(int action, int relayNumber)
{
    /* more magic over here */
    printf("Port :: %s\n", ttyPort);

}
// All python wrappers below

static PyObject*setPort(PyObject* self, PyObject* args)
{
    Py_INCREF(self)
    // Copy python argument to ttyPort
    if (!PyArg_ParseTuple(args, "s", &ttyPort))
        return NULL;

    printf("RelayModule :: Port set (%s)\n", ttyPort);

    Py_RETURN_NONE;
}

static PyObject*fanOff(PyObject* self, PyObject* args)
{
    //fanMode = 0;
    printf("RelayModule :: Fan off %s\n",ttyPort);
    if (setRelay(RELAY_OFF, 0) == 1){
        // more magic
    }
    Py_RETURN_NONE;
}
/* more functions over here */
static PyMethodDef RelayMethods[] =
{
     {"setPort", setPort, METH_VARARGS, "Set tty port."},
     {"fanOff", fanOff, METH_NOARGS, "Fan off."},
     {"fanHalf", fanHalf, METH_NOARGS, "Fan half speed."},
     {"fanFull", fanFull, METH_NOARGS, "Fan full on."},
     {"pumpOn", pumpOn, METH_NOARGS, "Pump on."},
     {"pumpOff", pumpOff, METH_NOARGS, "Pump off."},
     {"isPumpOn", isPumpOn, METH_NOARGS, "Check if pump is on."},
     {"getFanMode", getFanMode, METH_NOARGS, "Get fan mode."},
     {NULL, NULL, 0, NULL}
};

static struct PyModuleDef RelayDefs = { 
    PyModuleDef_HEAD_INIT,"RelayModule","A Python module that controls the Conrad 4ch relay card.", -1, RelayMethods 
};


PyMODINIT_FUNC PyInit_Relay(void)
{
    Py_Initialize();
    return PyModule_Create(&RelayDefs);
}

python代码例如:

import Relay

def settty():
    Relay.setPort("/dev/ttyUSB0")

def gettty():
    Relay.fanOff()

def doAll():
    Relay.setPort("/dev/ttyUSB0")
    Relay.fanOff()

settty()
gettty() #Error, prints 'Port :: [garbage]'
doAll() #works!

我怎么能以某种方式声明一个对象?在其他语言中,我会这样做:     RelayObj = new Relay()

或者我如何正确存储变量?

1 个答案:

答案 0 :(得分:0)

一种可能的解决方法是使用&#39; es&#39; PyArg_ParseTuple(args, "s", &ttyPort)中的格式说明符,而不是&#39; s&#39;。来自文档:

  

通常,当格式设置指向缓冲区的指针时,缓冲区由相应的Python对象管理,缓冲区共享此对象的生命周期

除非您使用&#39;。但是,您必须手动释放内存。