gpt4 book ai didi

python - 将 ctypes c_void_p 转换为 C 输出参数

转载 作者:太空宇宙 更新时间:2023-11-04 12:46:17 25 4
gpt4 key购买 nike

首先我知道Python ctypes, pass c_void_p as an out parameter to c function以及他们建议的解决方案,但我无法通过他们的回答使其发挥作用。反正我的问题是相似的......

我有一个 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(无)

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

最佳答案

以下内容:

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

关于python - 将 ctypes c_void_p 转换为 C 输出参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51377680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com