使用 SWIG 为 Python 包装 C++。 “向量”未声明

Posted

技术标签:

【中文标题】使用 SWIG 为 Python 包装 C++。 “向量”未声明【英文标题】:Using SWIG to wrap C++ for Python. 'vector' not declared 【发布时间】:2015-09-18 09:51:35 【问题描述】:

我正在尝试包装一个创建 3D 向量的 C++,以便我可以从 Python 调用它并可视化数据。我正在尝试使用 SWIG 进行包装,但是当我收到错误消息时

'vector' 未在此范围内声明

并且在我能想到的每个文件中都包含了“向量”,我不确定我必须做什么才能包含它。我创建了一组非常基本的测试函数来尝试查看问题出在哪里,它与我尝试运行的真实代码大致相似。

test.cpp

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

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

测试.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

谁能告诉我哪里出错了?

【问题讨论】:

你忘记了头文件 test.h 中的 std 命名空间。 【参考方案1】:

我已经找到了这个问题的答案,我会在这里发布更新的代码。问题有两个方面:

    SWIG 的 example.i 文件有误,需要包含“std_vector.i” 编译命令需要更多标志。

以下应该编译并运行。

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)

快乐矢量!

【讨论】:

以上是关于使用 SWIG 为 Python 包装 C++。 “向量”未声明的主要内容,如果未能解决你的问题,请参考以下文章

将 python 函数传递给 SWIG 包装的 C++ 代码

使用 SWIG 将 C++ <vector> 包装为 python NumPy 数组

SWIG C++ Python:通过引用或指针包装 int

无法为 c++ python 扩展编译 swig 生成的包装器

使用 SWIG 围绕 C++ 的 Python 包装器。参数类型无法识别

使用 SWIG 包装对象从 C++ 调用 Python 函数的最简洁方法是啥