python - 使用 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)
我根本不知道如何进行
解决方案
推荐阅读
- asp.net - SqlException:列名“NormalizedName”无效。列名“ConcurrencyStamp”无效。列名“NormalizedName”无效
- arrays - Spark:从 Scala 中的嵌套数组中删除第一个数组
- html - 如何使用 Bootstrap 4 在 div 旁边放置链接按钮
- xamarin.android - textview 可见性 xamarin android
- php - 规范化/标准路径根到 CLI/WEB
- java - 来自适配器类的访问意图
- bash - 如何在 shell 别名的每个参数之前添加“-e”?
- java - 使用抽象源 [java] 进行数据访问 - 用于傻瓜
- angular-components - 是否可以展开/折叠 MaterialListComponent 中的项目
- html - 显示图片来源