使用 Swig for C++ 模板生成包装函数时遇到问题

Having trouble Generating Wrapper function using Swig for C++ template

我正在尝试使用 swig 在一些现有的 C++ 方法上生成接口。我指的是以下 link 练习在 c++ 模板方法上生成

https://valelab4.ucsf.edu/svn/3rdpartypublic/swig/Examples/python/template/

文件:example.h

// Some template definitions

template<class T> T max(T a, T b) { return  a>b ? a : b; }

template<class T> class vector {
  T *v;
  int sz;
 public:
  vector(int _sz) {
    v = new T[_sz];
    sz = _sz;
  }
  T &get(int index) {
    return v[index];
  }
  void set(int index, T &val) {
    v[index] = val;
  }
#ifdef SWIG
  %extend {
    T getitem(int index) {
      return $self->get(index);
    }
    void setitem(int index, T val) {
      $self->set(index,val);
    }
  }
#endif
};

文件:example.i

%module example

%{
#include "example.h"
%}

/* Let's just grab the original header file here */
%include "example.h"

/* Now instantiate some specific template declarations */

%template(maxint) max<int>;
%template(maxdouble) max<double>;
%template(vecint) vector<int>;
%template(vecdouble) vector<double>;

setup.py

from distutils.core import setup, Extension 
#name of module 
name  = "example"
  
#version of module 
version = "1.0"
  
# specify the name of the extension and source files 
# required to compile this 
ext_modules = Extension(name='_example',sources=["example.i","example.h"]) 
  
setup(name=name, 
      version=version, 
      ext_modules=[ext_modules])

第一步:编译模块

python setup.py build_ext

第二步:安装到当前目录

python setup.py install --install-platlib=.

我在输出中看到以下错误

python setup.py build_ext
running build_ext
building '_example' extension
swigging example.i to example_wrap.c
swig -python -o example_wrap.c example.i
example.h:5: Warning 301: class keyword used, but not in C++ mode.
example.h:5: Error: Syntax error - possibly a missing semicolon.
error: command 'swig' failed with exit status 1

setup.py 中使用以下内容将 -c++ 选项传递给 SWIG。同时从源代码中删除 example.h,否则编译器会尝试编译 header。它已包含在生成的文件中。

ext_modules = Extension(name='_example', sources=["example.i"], swig_opts=['-c++'])