簡體   English   中英

使用 SWIG 將 numpy 數組元素(int)傳遞給 c++ int

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

I'd like to pass an integer element from a numpy array in python to a c++ function that catches it as a c++ integer using SWIG.

我在這里想念什么?

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;
}

測試器.py

import add_vector as vec
import numpy as np

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

OUTPUT

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'

Reading from the numpy.i manual ( https://docs.scipy.org/doc/numpy-1.13.0/reference/swig.interface-file.html#numpy-array-scalars-and-swig ), I copied the pyfragments.swg 文件進入我的工作目錄,但沒有任何改變。

我還嘗試了一些 %apply 指令來傳遞一個 int 和一個 int *,但這還沒有改變任何東西。 我不斷收到上面列出的相同類型錯誤。

版本: numpy 1.17.3; 痛飲2.0.12; python 3.7.3; numpy.i被復制到我的工作目錄中:/usr/lib/python2.7/dist-packages/instant/swig/numpy.i

已解決:有3個問題:

  1. The numpy.i file I copied over isn't compatible , and the compatible version isn't included in the installation package when you go through anaconda (still not sure why they'd do that).

Answer: Find which version of numpy you're running, then go here ( https://github.com/numpy/numpy/releases ) and download the numpy-[your_version].zip file, then specifically copy the numpy.i file ,在 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)};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM