【问题标题】:How to pass buffer address to c?如何将缓冲区地址传递给c?
【发布时间】:2021-05-08 06:51:34
【问题描述】:

我想将一个 numpy 数组缓冲区的地址传递给 c 函数, 我的 C 函数如下所示:

void print_float_buff(void *buff)
{
    float *b = (float *)buff;
    printf("Float Data: %f, %f, %f,\n", b[0], b[1], b[2]);
}

在python中我的代码是:

import numpy as np
fun=ctypes.CDLL("./mylib.so")
l = np.array([10., 12.6, 13.5], dtype = 'float')
address, flag = l.__array_interface__['data']
fun.print_float_buff(ctypes.c_void_p(address))

A 在我的 c 函数中得到完全不同的数据。地址好像不太好。如何将正确的地址传递给我的 C 函数?谢谢。

【问题讨论】:

    标签: python python-3.x numpy ctypes


    【解决方案1】:

    如果你正确指定.argtypes,ctypes 会告诉你类型错误。下面需要一个兼容c_float的一维数组:

    test.c

    #include <stdio.h>
    
    #ifdef _WIN32
    #   define API __declspec(dllexport)
    #else
    #   define API
    #endif
    
    API void print_float_buff(float *buff, size_t size)
    {
        for(size_t i = 0; i < size; ++i)
            printf("buff[%zu] = %f\n",i,buff[i]);
    }
    

    test.py

    from ctypes import *
    import numpy as np
    
    dll = CDLL('./test')
    dll.print_float_buff.argtypes = np.ctypeslib.ndpointer(c_float,ndim=1),c_size_t
    dll.print_float_buff.restype = None
    
    a = np.array([10., 12.6, 13.5])
    dll.print_float_buff(a,len(a))
    

    输出:

    Traceback (most recent call last):
      File "C:\test.py", line 9, in <module>
        dll.print_float_buff(a,len(a))
    ctypes.ArgumentError: argument 1: <class 'TypeError'>: array must have data type float32
    

    按照建议更改数组:

    a = np.array([10., 12.6, 13.5],dtypes='float32')
    

    输出:

    buff[0] = 10.000000
    buff[1] = 12.600000
    buff[2] = 13.500000
    

    【讨论】:

      【解决方案2】:

      我发现了问题。在 c 中,浮点大小为 4 个字节,而在 python 中,浮点大小为 8 个字节。 如果我这样分配数组:

      l = np.array([10., 12.6, 13.5], dtype = 'float32')
      

      效果很好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-13
        • 2014-08-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多