繁体   English   中英

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

[英]casting ctypes c_void_p to C output parameter

首先,我了解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))

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

bar类型的输出始终仅显示:

c_void_p(None)

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

下列:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM