使用struct和char从python中获取数据的Ctypes*

2024-09-23 22:26:54 发布

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

我需要将一个结构从python填充到C,如果我不知道返回的大小,我不知道如何将内存分配给字符指针

文件.c

typedef struct _CONFIG 
{
    int             id          ;
    char            *name       ;
} CONFIG, *PCONFIG;

config = malloc(sizeof(CONFIG));
getConfig(config);

int getConfig(PCONFIG config)
{
    PyObject *PyGetConfig;
    pargs = PyTuple_Pack(1
        , PyLong_FromVoidPtr(config)
        );
    if (PyCallable_Check(PyGetConfig)) {
        ppresult = PyObject_CallObject(PyGetConfig, pargs);
        PyErr_Print();
    } else {
        PyErr_Print();
    }
    printf("Result getConfig is %d\n",PyInt_AsLong(ppresult));
    return PyInt_AsLong(ppresult);
}

file.py

class _PyConfig(ctypes.Structure):
    _fields_ = [
        ('id',                      ctypes.c_int),
        ('name',                    ctypes.c_char_p)
    ]

def getConfig   (config):
    try:
        co = _PyConfig.from_address(config)
    except Exception as e:
        print( "Error creating config object -> Error Description: " + str(e))
        return -1
    co.id   = dict_Config['id']
    co.name = dict_Config['name']

如何为char *name分配内存


Tags: nameidconfigctypesintpyobjectcochar