【发布时间】:2019-10-23 17:44:27
【问题描述】:
我想将一个整数元素从 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 *,但这还没有改变任何东西。我不断收到上面列出的相同类型错误。
版本:numpy 1.17.3; 痛饮 2.0.12 ; 蟒蛇 3.7.3 ; numpy.i 正在从以下位置复制到我的工作目录:/usr/lib/python2.7/dist-packages/instant/swig/numpy.i
【问题讨论】:
-
在 tester.py 中
print(type(a[1]))显示了什么? -
@Flexo
-
那就是问题所在,但我不太确定 numpy 的正确修复方法是什么。也许让函数从
#include <stdint.h>获取int64_t? -
你的意思是把我的函数改成:void print_int(int64_t x); ?当我这样做时,我会得到:TypeError: in method 'print_int', argument 1 of type 'int64_t'
-
更新:我现在在我的机器上复制了其他适用于其他人的 swig/numpy.i 代码,我总是得到相同的 TypeError。我认为这很可能是我从 python2.7 文件夹中复制 numpy.i 的事实,或者存在其他版本兼容性问题。
标签: python c++ numpy swig typemaps