使用struct和char从python中获取数据的Ctypes*
我需要将一个结构从python填充到C,如果我不知道返回的大小,我不知道如何将内存分配给字符指针 文件.c使用struct和char从python中获取数据的Ctypes*,python,pointers,ctypes,Python,Pointers,Ctypes,我需要将一个结构从python填充到C,如果我不知道返回的大小,我不知道如何将内存分配给字符指针 文件.c typedef struct _CONFIG { int id ; char *name ; } CONFIG, *PCONFIG; config = malloc(sizeof(CONFIG)); getConfig(config); int getConfig(PCONFIG config
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
分配内存?co.name=ctypes.c\u char\u p(dict\u Config['name'])应该适用于bytes对象。如果参数是字符串,则首先需要进行编码。没有一个代码段可以编译(肉眼可以看到)。