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

避免C编写的Python库的垃圾收集,python,c,python-c-api,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) co

我正在努力使用我的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);
}
我怎样才能声明一个对象?在其他语言中,我会: RelayObj=新继电器()


或者如何正确存储变量?

一个可能的解决方案是在
PyArg\u语法元组(args,“s”和&ttyPort)
中使用“es”格式说明符,而不是“s”。从文件:

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


除非你用“es”。但是,您必须手动释放内存。

将其嵌入到对象中,并使函数成为成员函数。我认为主要问题之一是,我将如何使用您当前的实现来做到这一点,尝试将
PyModule\u Create
的返回值存储在static var中。我怀疑立即返回它可能会导致优化器立即删除它(或者禁用编译器优化以查看它是否确实干扰)。例如:
类myrelay(Relay):。。。def uuu init uuu(self,name):…
(加上其他函数)。然后您可以使用
thisrelay=myrelay('/dev/ttyS0')
类myrelay(Relay):def\uu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu,但是,我还需要像这样添加编码:
if(!PyArg_ParseTuple(args,“es”,“utf-8”和&ttyPort))
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!