传递对象作为函数的参数

时间:2012-04-26 13:14:05

标签: python object dll ctypes

DLL(C语言)link("parameters", &connection);中有一个函数,它接受一个字符串参数并初始化一个连接。

有一个函数connect(connection),其中connection是通过调用link()初始化的对象。

我将Python连接对象传递给函数connect()作为参数

connection_t = ctypes.c_uint32
link = mydll.link
link.argtypes=(ctypes.c_char_p, ctypes.POINTER(connection_t) )
connect = mydll.connect
connect.argtypes=(connection_t,)
...
connection = connection_t()
link ("localhost: 5412", ctypes.byref(connection))
...

但是如果我将'connection'对象传递给mydll库的任何其他函数,该函数返回一个值,但该值不正确。

func=mydll.func
status_t=ctypes.c_uint32
status=status_t()
func.argtypes=(ctypes.c_ulong,ctypes.POINTER(status_t))
result=func(connection, ctypes.byref(status))

在此示例result=0中,但在此代码的C变体中,我收到正确的值(不是0)

为什么?

1 个答案:

答案 0 :(得分:0)

根据您对C apis的评论:

link(const char* set, conn_type* connection );
func(conn_type* connection, uint32_t* status);

由于func采用指向连接类型的指针,因此代码应为:

mydll=ctypes.CDLL('mydll')
connection_t = ctypes.c_uint32
link = mydll.link
link.argtypes=(ctypes.c_char_p, ctypes.POINTER(connection_t) )
connection = connection_t()
link("localhost: 5412", ctypes.byref(connection))

func=mydll.func
status_t=ctypes.c_uint32
status=status_t()
func.argtypes=(ctypes.POINTER(connection_t),ctypes.POINTER(status_t))
result=func(ctypes.byref(connection), ctypes.byref(status))