首页 > 解决方案 > 将 ctypes c_void_p 转换为 C 输出参数

问题描述

首先我了解Python ctypes,将 c_void_p 作为 out 参数传递给 c 函数及其建议的解决方案,但我无法通过他们的回答使其工作。反正我的问题是类似的...

我有一个 C 函数,我想使用 ctypes 用 Python 进行包装。它接受

error_t foo(int a,void ** bar)

bar作为输出参数。

我的 Python ctypes 看起来像链接线程中描述的那样:

bar = c_void_p()
foo(guids, byref(bar))

我不知道我做错了什么或不同......我有点无能为力......

always类型的输出bar只显示:

c_void_p(None)

感谢您的任何帮助或想法...

标签: pythonc++python-3.xctypesout

解决方案


以下:

import os
file=open("/tmp/1.c","w")
# you didn't provide the implementation of foo (why?) so i needed to write it myself
file.write(
"typedef int error_t;"
"error_t foo(int a,void ** bar) {"
"       *bar = a;"
"       return a * 2;"
"}"
)
file.close()
os.system("gcc -Wno-int-conversion -shared -o /tmp/lib1.so.1 /tmp/1.c")

import ctypes
lib1 = ctypes.cdll.LoadLibrary("/tmp/lib1.so.1")
guids = 1000

# the code you provided us
bar = ctypes.c_void_p()
ret = lib1.foo(guids, ctypes.byref(bar))
# end of the code you provided us

print("foo(" + str(guids) + ", " + str(ctypes.byref(bar)) + ") = " + str(ret))
print("And bar has the value: " +  str(bar));

打印出来:

foo(1000, <cparam 'P' (0x7ffa3414ee68)>) = 2000
And bar has the value: c_void_p(1000)

该脚本将一个简单的 C 程序编译为共享库:

typedef int error_t;
error_t foo(int a,void ** bar) {
       *bar = a;
       return a * 2;
}

然后使用 python 中的 ctypes 运行该函数。
正如预期的那样,调用foo(1000, ...)返回2000并将值设置为void *barto 1000。所以你做的python调用没问题,检查函数。可能你的foo()集合是barto的值NULL


推荐阅读