SWIG包装C ++ for Python:将字符串列表转换为STL字符串的STL向量 [英] SWIG wrapping C++ for Python: translating a list of strings to an STL vector of STL strings

查看:287
本文介绍了SWIG包装C ++ for Python:将字符串列表转换为STL字符串的STL向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to wrap a C++ function with SWIG which accepts a vector of STL strings as an input argument:

#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函数, ':

I want to wrap this into a Python function available in a module called `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++']),
                         ],
  )

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

and then import it and try to run it, I get this error:

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不提供默认的typemap Python字符串列表和STL字符串的C ++ STL向量。我觉得这是他们可能提供的地方默认情况下,但也许我不知道正确的文件包括。

I'm guessing this is saying that SWIG doesn't provide a default typemap for translating between a Python list of Python strings and a C++ STL vector of STL strings. I feel like this is something they might provide somewhere by default, but perhaps I don't know the right file to include. So how can I get this to work?

推荐答案

您需要告诉SWIG您需要一个向量字符串typemap。

You need to tell SWIG that you want a vector string typemap. It does not magically guess all the different vector types that can exist.

这是Schollii提供的链接:

This is at the link provided by 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"

这篇关于SWIG包装C ++ for Python:将字符串列表转换为STL字符串的STL向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆