【问题标题】:Reading array returned by c function in ctypes在ctypes中读取c函数返回的数组
【发布时间】:2013-08-04 15:20:28
【问题描述】:

我有一些 C 代码,我正试图从 python 中的 ctypes 访问这些代码。一个特定的函数看起来像这样:

float *foo(void) {
    static float bar[2];
    // Populate bar
    return bar;
}

我知道这不是编写 C 的理想方式,但在这种情况下它可以完成工作。我正在努力编写 python 来获取响应中包含的两个浮点数。我对作为单个变量的返回值很好,但我无法从 ctypes 文档中找出如何处理指向数组的指针。

有什么想法吗?

【问题讨论】:

  • 我猜你不应该在堆栈上返回一个变量,你应该 malloc 一个然后返回。

标签: python c ctypes


【解决方案1】:

将 restype 指定为 [POINTER][1](c_float):

import ctypes

libfoo = ctypes.cdll.LoadLibrary('./foo.so')
foo = libfoo.foo
foo.argtypes = ()
foo.restype = ctypes.POINTER(ctypes.c_float)
result = foo()
print(result[0], result[1])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    相关资源
    最近更新 更多