python中定义结构体通过继承_ctypes中的Structure类,标准写法如下:
c:
struct beer_recipe
{
int amt_barley;
int amt_water;
};
struct beer_recipe
{
int amt_barley;
int amt_water;
};
python:
class beer_recipe(Structure):
_fields_ = [
("amt_barley",c_int),
("amt_water",c_int),
]
class beer_recipe(Structure):
_fields_ = [
("amt_barley",c_int),
("amt_water",c_int),
]
看一个libsvm中的例子:
class svm_node(Structure):
_names = ["index", "value"]
_types = [c_int, c_double]
_fields_ = genFields(_names, _types)
def __str__(self):
return '%d:%g' % (self.index, self.value)
class svm_node(Structure):
_names = ["index", "value"]
_types = [c_int, c_double]
_fields_ = genFields(_names, _types)
def __str__(self):
return '%d:%g' % (self.index, self.value)
def genFields(names, types):
return list(zip(names, types))
def genFields(names, types):
return list(zip(names, types))
svm_node实际上就是这样一个东西:
_fields_ = [
("index",c_int),
("value",c_double),
]
_fields_ = [
("index",c_int),
("value",c_double),
]
即一个index对应一个value,分别是int和double类型。只不过是用了zip这样的少见的函数。