将ctypes c_void_p强制转换为C输出参数

时间:2018-07-17 09:22:29

标签: python c++ python-3.x ctypes out

首先,我了解Python ctypes, pass c_void_p as an out parameter to c function及其建议的解决方案,但是我无法使他们的答案生效。我的问题还是类似...

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

bar

bar = c_void_p() foo(guids, byref(bar)) 作为输出参数。

我的Python ctypes看起来像链接线程中所述:

bar

我不知道我做错了什么或有所不同...有点无知...

c_void_p(None)类型的输出始终仅显示:

{{1}}

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

1 个答案:

答案 0 :(得分:0)

以下内容:

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 *bar的值设置为1000。因此,您执行的python调用就可以了,请检查函数。可能是您的foo()bar的值设置为NULL