【问题标题】:passing object as an argument of function将对象作为函数的参数传递
【发布时间】:2012-04-26 13:14:05
【问题描述】:

有一个来自 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)

为什么?

【问题讨论】:

  • 你确定你应该看result而不是status吗?
  • connection_tctypes.c_uint32,但第一个 func.argtypesctypes.c_ulong?
  • 牦牛,对不起,我的意思是“状态”值。但如果“状态”不正确,那么“结果”值也不正确。
  • martineau,我更正了第一个 'func.argtypes'(connection_t 是 ctypes.c_uint32),但没有帮助
  • 发布的代码看起来没问题。将函数的确切 C 标头定义和代码发布到 init mydll。你是用CDLL还是WinDLL来初始化mydll?

标签: python object dll ctypes


【解决方案1】:

根据您描述 C api 的评论:

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))

【讨论】:

    猜你喜欢
    • 2018-02-23
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多