首页 > 解决方案 > 使用 ctypes 将 2D C 数组转换为 Numpy 数组

问题描述

您好我正在尝试编写一个简单的 C 函数,该函数接受两个输入 (m,n) 并创建一个 2D - 指针数组。现在我想调用该函数并从指针Ctypes创建一个。numpy array但是,我不确定如何继续 - 并在调用np.frombuffer- 函数时遇到错误。任何帮助都是值得的

c-文件

#include <stdio.h>
#include <stdlib.h>

#define RANDOM_RANGE 50

typedef struct {
    float val;
} cell;

cell **matrixMake(int m, int n){

    // the rows
    cell **pRow = (cell **)malloc(m* sizeof(cell *));
    // the cols
    for (int i = 0; i < m; i++){
        pRow[i] = (cell *)malloc(n * sizeof(cell));
    }

    for (int i = 0; i < m; i++){
        for (int j = 0; j < n; j++){
            pRow[i][j].val = (float) (rand() % RANDOM_RANGE);
        }
    }

    return pRow;
}

对应的 Python 文件

import numpy as np
from numpy.ctypeslib import ndpointer
from ctypes import *



class CELL(Structure):
    _fields_ = [ ('val', c_float) ]

libc = CDLL("c_arr_multi.so")

libc.matrixMake.argtypes = [ c_int, c_int ]
libc.matrixMake.restype = POINTER(POINTER(CELL))
res = libc.matrixMake(6, 3)

x = np.frombuffer((c_float * 6 * 3).from_address(libc.matrixMake(6, 3)), np.float32).copy()

print(x)

我根本不知道如何进行

标签: pythoncnumpyctypes

解决方案


推荐阅读