我想调用坐在共享对象从python的C函数,并且使用ctypes似乎是完成此操作的最佳方法。我不得不派生类型传递给该函数,用下面的函数原型:使用ctypes调用结构指针
int MyFunc (Config *config, int *argc, char **argv)
的Config
结构被定义为
typedef struct{ char *some_filename ;
char **some_other_filenames ;
int some_value ;
Coord resolution;
} Config;
Coord
被定义为
typdef struct { double x, y, area } Coord ;
蛇皮ctypes的代码然后只是对派生类型的重写:
class COORD (ctypes.Structure):
_fields = [ ("lon",ctypes.c_double),\
("lat", ctypes.c_double),\
("area", ctypes.c_double)]
coords = COORD()
class CONFIG(ctypes.Structure):
_fields = [ ("some_filename", ctypes.c_char_p),\
("some_other_filenames", ctypes.c_char_p('\0' * 256)),\
("some_value", ctypes.c_int),\
("resolution", coords) ]
我然后设置论据MyFunc
:
MyFunc.argtypes = [ctypes.byref(CONFIG) , ctypes.POINTER(ctypes.c_int),\
ctypes.POINTER (ctypes.c_char_p)]
MyFunc.restype = ctypes.c_int
myargv = ctypes.c_char_p * 2
argv = myargv("One", "Two")
argc = ctypes.c_int (2)
retval = MyFunc ( ctypes.byref(config), ctypes.byref(argc), ctypes(argv))
然而,这会产生一个段错误。任何人有任何想法这里发生了什么?
UPDATE 在我的问题中有一个拼写错误,从剪切和粘贴,问题仍然存在!
你是对的,整数成员失踪。我现在编辑了它,但这只是我无法切割和粘贴!谢谢! – Jose 2009-12-02 21:37:00