使用SWIG将numpy数组元素(int)传递给c ++ int

其他性

我想将整数元素从python中的numpy数组传递给c函数,该函数使用SWIG将其捕获为c ++整数。

我在这里想念什么?

add_vector.i

%module add_vector
%{
    #define SWIG_FILE_WITH_INIT
    #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION  // gets rid of warning
    #include "add_vector.h"
%}

%include "numpy.i"
%init %{
import_array();
%}

%include "add_vector.h"

add_vector.h

#include <iostream>

void print_int(int x);

add_vector.cpp

#include "add_vector.h"

void print_int(int x) {
    std::cout << x << std::endl;
}

测试器

import add_vector as vec
import numpy as np

a = np.array([1,2,3])
print(a[1])
vec.print_int(a[1])

输出值

2
Traceback (most recent call last):
  File "tester.py", line 6, in <module>
    vec.print_int(a[1])
TypeError: in method 'print_int', argument 1 of type 'int'

从numpy.i手册(https://docs.scipy.org/doc/numpy-1.13.0/reference/swig.interface-file.html#numpy-array-scalars-and-swig阅读pyfragments.swg文件放入我的工作目录中,但没有任何更改。

我也尝试了一些%apply指令来传递int和int *,但这还没有改变任何东西。我不断收到上面列出的TypeError。

版本:numpy 1.17.3; swig 2.0.12; python 3.7.3; numpy.i从以下位置复制到我的工作目录中:/usr/lib/python2.7/dist-packages/instant/swig/numpy.i

其他性

解决了!有3个问题:

  1. 我复制过来的numpy.i文件不兼容,并且在通过anaconda进行安装时,兼容版本未包含在安装包中(仍然不确定他们为什么这样做)。

答:查找您正在运行的numpy版本,然后转到此处(https://github.com/numpy/numpy/releases)并下载numpy- [your_version] .zip文件,然后专门复制numpy.i文件,位于numpy- [您的版本] / tools / swig /中。现在,将numpy.i粘贴到您的项目工作目录中。

  1. 默认情况下,numpy使long类型的整数变长。因此,在tester.py文件中,我需要编写:a = np.array([1,2,3],dtype = np.intc)

  2. 需要在add_vector.i中将numpy int转换为c ++ int 这可以通过在%include“ add_vector.h”行上方使用%apply指令来完成:%apply(int DIM1){(int x)};

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章