python - 将 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)
感谢您的任何帮助或想法...
解决方案
以下:
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
to 1000
。所以你做的python调用没问题,检查函数。可能你的foo()
集合是bar
to的值NULL
。
推荐阅读
- vue.js - Vue 服务器端渲染和 Twitter 卡片
- python - 无法更改openpyxl上的字体
- .net - 带有 teradada 提供程序的 MVC ER
- kotlin - 根据 Kotlin 类生成 GraphQL 类型并转换类型
- c# - Google Tasks API BatchRequest 触发“批处理请求中的重复请求 ID”
- reactjs - React + FontAwesome + Bootstrap
- unreal-engine4 - 如何运行我的旧虚幻引擎 4 项目?
- c - 如何运行本教程 gluonfx:build 命令的结果?
- leakcanary - 为什么 LeakCanary 不推荐弱引用
- jquery - 在页面加载之前显示 ajax 加载器