簡體   English   中英

使用SWIG為Python包裝C ++。 'vector'沒有聲明

[英]Using SWIG to wrap C++ for Python. 'vector' not declared

我正在嘗試包裝一個創建3D矢量的C ++,以便我可以從Python調用它並可視化數據。 我正在嘗試用SWIG包裝,但是當我這樣做時,我收到錯誤消息

'vector'未在此范圍內聲明

並且將“vector”包含在我能想到的每個文件中我不知道我要做什么來包含它。 我已經創建了一組非常基本的測試函數來嘗試查看問題所在,它與我正在嘗試運行的實際代碼大致相似。

TEST.CPP

#include <vector>
#include <iostream>
using namespace std;

vector<int> testfunction(vector <int>& value){
  cout <<"Running\n";
  return value;
}

test.h

#ifndef TEST_H_    // To make sure you don't declare the function more than once by including the header multiple times.
#define TEST_H_
#include <vector>
#include <iostream>

vector<int> testfunction(vector <int>& value);

test.i

/*test.i*/
%module test
%{
#include "test.h"
#include <vector>
%}

vector<double> testfunction(vector<double> value);

編譯我正在使用以下內容

    g++ -g -ggdb -c -std=c++0x -I /include/python2.7 -o run test.cpp
    swig -c++ -python test.i
    gcc -fpic -c test.cpp test_wrap.cxx -I /include/python2.7
    gcc -shared test.o test_wrap.o -i _test.so

誰能告訴我哪里出錯了?

我找到了這個問題的答案,我將在這里發布更新的代碼。 問題有兩個:

  1. SWIG的example.i文件錯誤,需要包含“std_vector.i”
  2. 編譯命令需要更多標志。

以下應編譯並運行。

example.h文件

    #ifndef TEST_H_
    #define TEST_H_
    #include <vector>
    #include <iostream>

    std::vector<int> testfunction(std::vector <int>& value);

    #endif

example.cpp

    #include <vector>
    #include <iostream>

    std::vector<int> testfunction(std::vector <int>& value){
      std::cout <<"Running\n";
      return value;
    }

example.i

%module example
%{
#include "example.h"
%}

%include "std_vector.i"
// Instantiate templates used by example
namespace std {
   %template(IntVector) vector<int>;
   %template(DoubleVector) vector<double>;
}

// Include the header file with above prototypes
%include "example.h"

生成文件

所有:

    g++ -g -ggdb -std=c++0x -I include/python2.7 -o run example.cpp example_run.cpp
    swig -c++ -python example.i

    gcc -fpic -c example.cpp example_wrap.cxx -I include/python2.7
    gcc -Wl,--gc-sections -fPIC -shared -lstdc++ example.o example_wrap.o -o _example.so

Python調用:

>>> import example as ex
>>> iv=ex.IntVector(1)
>>> ex.testfunction(iv)

快樂矢量!

暫無
暫無

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

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