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

Passing numpy array element (int) to c++ int using SWIG

本文关键字:c++int int SWIG numpy 数组元素 使用      更新时间:2023-10-16

我想将一个整数元素从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;
}

tester.py

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-数组标量和swig(,我将pyfragments.swg文件复制到我的工作目录中,但没有任何更改。

我还尝试了许多%apply指令来传递int和int*,但这还没有改变任何事情。我一直收到上面列出的相同类型错误。

版本:numpy1.17.3swig2.0.12python3.7.3numpy.i正在从/usr/lib/python2.7/dist packages/simmet/swig/numpy.i 复制到我的工作目录中

已解决!共有3个问题:

  1. 我复制的numpy.i文件不兼容,而且当你使用anaconda时,安装包中也不包括兼容版本(仍然不确定他们为什么会这样做(

答案:找到您正在运行的numpy的版本,然后转到此处(https://github.com/numpy/numpy/releases)并下载numpy-[your_version].zip文件,然后专门复制numpy.i文件,该文件位于numpy--[your_version]/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(}