python - swig numpy 多矩阵和数组输入

标签 python c numpy swig

我正在尝试使用 SWIG 和 Numpy 类型映射将一个小型 C 函数连接到 python 中

这个函数定义如下

void nw(int* D, int Dx, int Dy, int* mat, int mx, int my, char *xstr, int xL,char *ystr, int yL);

而我的接口(interface)文件如下

%module nw

%{
    #define SWIG_FILE_WITH_INIT
    #include "nw.h"
%}

%include "numpy.i"

%init %{
  import_array();
%}
/*type maps for input arrays and strings*/
%apply (int* INPLACE_ARRAY2, int DIM1, int DIM2) {(int* D, int Dx, int Dy)}
%apply (int* IN_ARRAY2, int DIM1, int DIM2) {(int* mat, int mx, int my)}
%apply (char* IN_ARRAY, int DIM1){(char *xstr, int xL),(char *ystr, int yL)}

%include "nw.h"

为了测试它,我使用了以下输入

D = numpy.zeros((5,5),numpy.int)
mat = numpy.array([[1, 0, 0, 0, 0, 0],
                   [0, 1, 0, 0, 0, 0],
                   [0, 0, 1, 0, 0, 0],
                   [0, 0, 0, 1, 0, 0],
                   [0, 0, 0, 0, 1, 0],
                   [0, 0, 0, 0, 0, 1]],numpy.int)
x = numpy.array(list("ABCD"))
y = numpy.array(list("ABCD"))
import nw
nw.nw(D,mat,x,y)

但是当我运行它时,我得到以下信息

TypeError: nw() takes exactly 6 arguments (4 given)

我真的很困惑这些参数是如何定义的。这里有没有人知道为什么有 6 个参数以及这些参数是什么?谢谢!

最佳答案

好吧,我想我已经找到问题了。

事实证明,SWIG 真的不喜欢我为 cstring 制作的应用指令。

我应该改为使用以下指令。

%apply (char *STRING, int LENGTH) {(char *xstr, int xL),(char *ystr, int yL)}

应该更仔细地看食谱哈哈

关于python - swig numpy 多矩阵和数组输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18027950/

相关文章:

c - 我使用 'exit(EXIT_FAILURE);' ,但随后出现错误

c++ - 如何优雅地处理来自 C++ 代码的 C 回调?

python - 将 Python 方法转换为 C 扩展的好处?

python - 循环 2 个一维数组以在 numpy 中创建二维数组

python - 无需 for 循环即可修改 Numpy 2D 数组中特定位置的元素

python - 使用 Bokeh 绘图时,如何自动循环显示调色板?

python - 使用 Python 连接到 Redis 集群(在 Docker 中)

python - 读取大型机 EBCDIC 文件

python - 字符串和日期时间对象互换

Python - 元组和内存管理