c-当我从python 3调用2d数组函数时出现输出问题



我是个编码新手。我的系统是win10 64位。我正在使用CodeBlocks编写C代码。此外,我使用的是Python 3.10。这是我的C代码。此函数将值0.99添加到矩阵的所有元素。我想从python 3调用这个函数。我的C文件是;

cab2.c

#include <stdio.h>
#include <stdlib.h>
c_bes(const int ** s, int R) {
float** nrm=(float**)malloc(R*sizeof(int*));
for (int i = 0; i < R; i++){
nrm[i]=(float*)malloc(sizeof(int)*R);
}
for( int i=0; i<R; i++){
for(int j=0; j<3; j++){
nrm[i][j]= 0.9;
}
}
return nrm;
}

它在C语言中成功地将0.9值与n*m零矩阵相加。如上所述,为了在python中使用此函数,我使用此命令编译了此代码,并编写了如下python代码。

gcc -o c_bes.so --shared -fPIC cab2.c 

我的python代码;

测试

from ctypes import c_void_p, c_double, c_int, cdll, c_float
from numpy.ctypeslib import ndpointer
import numpy as np
row=2
col=3
orn = np.matrix([[0, 0, 0],
[0, 0, 0]])
print (orn)
lib = cdll.LoadLibrary("C:/Users/Casper/Desktop/Cfunc_in_pyt_2/c_bes.so")
c_bes = lib.c_bes
c_bes.restype = ndpointer(dtype=c_float, shape=(row,col))
res = c_bes(  c_void_p(orn.ctypes.data),  c_int(row)  )
print(res)

我的输出是;

[[0 0 0]
[0 0 0]]
[[-2.8212709e-34  8.6600245e-43 -2.8212783e-34]
[ 8.6600245e-43  0.0000000e+00  0.0000000e+00]]

如上所示,这给了我错误的输出!所有矩阵元素必须为0.9!我怎么了?尽管我付出了所有的努力,我还是不能成功!请帮帮我。

要求:对于C函数,0.99要加到矩阵的所有元素上。矩阵来自Python。

有几个问题:

  • C函数中的参数s似乎是预期的Python矩阵,但该参数在C函数中根本没有使用
  • s的类型是错误的,假设一个连续数组,它应该只是float *
  • c_bes没有声明的返回类型,可以使用void,因为矩阵元素可以就地操作
  • 如果您更喜欢在C端动态分配内存,则应该使用正确的大小,因此如果您想使用浮点数组,则不应该使用sizeof(int),而应该使用sizeof(float)
  • 如果使用了动态内存,您也应该在使用后释放它
  • 也许可以使用更好的命名来提高代码的可读性,例如matrixcolsrows
  • 使用编译器选项-Wall -Wextra,您可以得到关于代码中可能存在的问题的有用警告,请使用
  • = 0.9分配一个固定值,但实际上您想向矩阵元素添加一些内容,所以使用加法分配+= 0.99f。末尾的f表示要使用浮点常量而不是双常量
  • 在Python中,函数参数的类型可以使用argtypes来描述
  • 使用dtype可以指定所需类型的矩阵元素

如果您将刚才列出的要点应用到示例代码中,它可能看起来像这样:

cab2.h

#ifndef C_BES_LIBRARY_H
#define C_BES_LIBRARY_H
void c_bes(float *input, int rows, int cols);
#endif //C_BES_LIBRARY_H

cab2.c

#include "cab2.h"
void c_bes(float *matrix, int rows, int cols) {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
matrix[r * cols + c] += 0.99f;
}
}
}

Python

from ctypes import c_int, cdll, c_float
from numpy.ctypeslib import ndpointer
import numpy as np
rows = 2
cols = 3
lib = cdll.LoadLibrary("C:/Users/Casper/Desktop/Cfunc_in_pyt_2/c_bes.so")
c_bes = lib.c_bes
c_bes.argtypes = [ndpointer(c_float, flags="C_CONTIGUOUS", shape=(rows, cols)), c_int, c_int]
orn = np.matrix([[1, 2, 3],
[4, 5, 6]], dtype=np.float32)
c_bes(orn, rows, cols)
print(orn)

测试

然后,上面的代码在调试控制台上输出以下内容:

[[1.99 2.99 3.99]
[4.99 5.99 6.99]]

请注意,我已经更改了输入矩阵,以便可以看到对输入矩阵的值执行了正确的操作。

最新更新