使用SWIG将numpy数组元素(int)传递给c++int
Passing numpy array element (int) to c++ int using SWIG
我想将一个整数元素从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个问题:
- 我复制的numpy.i文件不兼容,而且当你使用anaconda时,安装包中也不包括兼容版本(仍然不确定他们为什么会这样做(
答案:找到您正在运行的numpy的版本,然后转到此处(https://github.com/numpy/numpy/releases)并下载numpy-[your_version].zip文件,然后专门复制numpy.i文件,该文件位于numpy--[your_version]/tools/swig/中。现在将numpy.i粘贴到您的项目工作目录中。
-
默认情况下,numpy使类型为long的整数变长。所以在tester.py文件中,我需要写:a=np.array([1,2,3],dtype=np.intc(
-
需要在add_vector.i中将numpy int转换为c++int。这可以通过在%include"add_vector.h"行正上方使用%apply指令来完成:%apply(int DIM1({(int x(}
- 多维数组 C++ 中数组下标的类型"int[int]"无效
- 错误:数组下标的类型"int[int]"无效
- 调用'myStud::myStud(int, const char [5], int, int, int)'没有匹配函数
- C++ - 如何使用<int> <int>STL 算法功能在矢量<vector>中找到矢量?
- 如何在矢量<矢量>中推送 int<int>
- 无法将 int (*(int))(int) 转换为 int (*(int))(int)
- 使用类型别名,例如使用 A = int(int)
- map int<-->int, 1:N, 已知边界
- int(int)& 或 int(int) const &是什么类型?
- 数组下标编译的无效类型'int[int]'由于 -Wfatal 错误而终止
- 'int main(int, int, std::__cxx11::string, std::__cxx11::string)'只需要零或两个参数 [-Wmain]
- 数组下标的无效类型INT [INT]
- 在开关案例节点中,将const int int指向int
- int func(function <int(int)> F, int x)
- 构造一对 unique_ptr 和<int> int
- C 构造函数从char*到int []/int*
- 我正在声明一个自定义优先级队列,包括 pair<pair<int,int>int >,如何清除它?
- C++错误:与调用'(std::list<int>) (int&)'不匹配
- 使用4用于循环的4矩阵上的数组下标的“ int [int]类型”
- 对"(std::vector<std::vector<int> >) (int, std::vector<int>)"的调用不匹配