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

问题描述 投票:0回答:1

我想将整数从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-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

python c++ numpy swig typemaps
1个回答
0
投票

已解决!有3个问题:

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

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

  1. 默认情况下,numpy将整数类型设为long。所以在tester.py文件中,我需要写:a = np.array([1,2,3],dtype = np.intc)

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

© www.soinside.com 2019 - 2024. All rights reserved.