将 ctypes c_void_p 转换为 C 输出参数
casting ctypes c_void_p to C output parameter
首先我知道 和他们建议的解决方案,但我无法通过他们的回答使其发挥作用。反正我的问题是相似的...
我有一个 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
。
首先我知道
我有一个 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
。