【问题标题】:SWIG wrapping C++ for Python: translating a list of strings to an STL vector of STL stringsSWIG 为 Python 包装 C++:将字符串列表转换为 STL 字符串的 STL 向量
【发布时间】:2012-01-18 03:23:32
【问题描述】:

我想用 SWIG 包装一个 C++ 函数,它接受一个 STL 字符串向量作为输入参数:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

void print_function(vector<string> strs) {
  for (unsigned int i=0; i < strs.size(); i++)
  cout << strs[i] << endl;
}

我想将它包装到一个 Python 函数中,该函数在一个名为 `mymod' 的模块中可用:

/*mymod.i*/
%module mymod
%include "typemaps.i"
%include "std_string.i"
%include "std_vector.i"

%{
 #include "mymod.hpp"
%}

%include "mymod.hpp"

当我用

构建这个扩展时
from distutils.core import setup, Extension

setup(name='mymod',
  version='0.1.0',
  description='test module',
  author='Craig',
  author_email='balh.org',
  packages=['mymod'],
  ext_modules=[Extension('mymod._mymod',
                         ['mymod/mymod.i'],
                         language='c++',
                         swig_opts=['-c++']),
                         ],
  )

然后导入它并尝试运行它,我得到这个错误:

Python 2.7.2 (default, Sep 19 2011, 11:18:13) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymod
>>> mymod.print_function("hello is seymour butts available".split())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: in method 'print_function', argument 1 of type 'std::vector<  std::string,std::allocator< std::string > >'
>>> 

我猜这是说 SWIG 没有提供用于在 Python 字符串的 Python 列表和 STL 字符串的 C++ STL 向量之间进行转换的默认类型映射。我觉得这是他们默认可能在某处提供的东西,但也许我不知道要包含的正确文件。那么我怎样才能让它工作呢?

提前致谢!

【问题讨论】:

    标签: c++ python string vector swig


    【解决方案1】:

    SWIG 确实支持将列表传递给将向量作为值或 const 向量引用的函数。 http://www.swig.org/Doc2.0/Library.html#Library_std_vector 的示例显示了这一点,我看不出您发布的内容有什么问题。还有其他问题; python 找到的 DLL 不是最新的,标头中的 using namespace std 混淆了执行类型检查的 SWIG 包装器代码(请注意,.hpp 中的“使用命名空间”语句通常是禁止的,因为它会提取所有内容从 std 到全局命名空间)等。

    【讨论】:

    • 我在有/没有using namespace std; 的情况下都试过了,没有任何区别。我同意应该在没有using 语句的情况下编写标题。我担心的是您链接的示例是针对原始向量的,例如整数和双精度数;我无法在网上找到任何用于包装矢量,甚至矢量
    • 我的编辑是否针对其他矢量类型?如果不是,我会遗漏一些明显的东西。
    【解决方案2】:

    你需要告诉 SWIG 你想要一个向量字符串类型映射。它不会神奇地猜测所有可能存在的不同向量类型。

    这是 Schollii 提供的链接:

    //To wrap with SWIG, you might write the following:
    
    %module example
    %{
    #include "example.h"
    %}
    
    %include "std_vector.i"
    %include "std_string.i"
    
    // Instantiate templates used by example
    namespace std {
       %template(IntVector) vector<int>;
       %template(DoubleVector) vector<double>;
       %template(StringVector) vector<string>;
       %template(ConstCharVector) vector<const char*>;
    }
    
    // Include the header file with above prototypes
    %include "example.h"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 2021-12-04
      • 2020-02-27
      相关资源
      最近更新 更多