我想从Python中调用一个位于共享对象中的C函数,并且使用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 ;
Python的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))
然而,这会导致一个段错误。有人知道这里发生了什么吗?
更新 由于剪切和粘贴的原因,我的问题中有一个错别字,问题仍然存在!