2012-01-17 33 views
0

我有一个SWIG生成的函数,如下所示:SWIG倍率功能或修改C++结果对象

SWIGINTERN PyObject *_wrap_StrVector___getitem____SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { 
    PyObject *resultobj = 0; 
    std::vector<std::string> *arg1 = (std::vector<std::string> *) 0 ; 
    PySliceObject *arg2 = (PySliceObject *) 0 ; 
    void *argp1 = 0 ; 
    int res1 = 0 ; 
    PyObject * obj0 = 0 ; 
    PyObject * obj1 = 0 ; 
    std::vector< std::string,std::allocator<std::string> > *result = 0 ; 

    if (!PyArg_ParseTuple(args,(char *)"OO:StrVector___getitem__",&obj0,&obj1)) SWIG_fail; 
    res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_std__vectorT_std__string_std__allocatorT_std__string_t_t, 0 | 0); 
    if (!SWIG_IsOK(res1)) { 
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "StrVector___getitem__" "', argument " "1"" of type '" "std::vector<std::string> *""'"); 
    } 
    arg1 = reinterpret_cast< std::vector<std::string> * >(argp1); 
    { 
    if (!PySlice_Check(obj1)) { 
     SWIG_exception_fail(SWIG_ArgError(SWIG_TypeError), "in method '" "StrVector___getitem__" "', argument " "2"" of type '" "PySliceObject *""'"); 
    } 
    arg2 = (PySliceObject *) obj1; 
    } 
    try { 
    result = (std::vector< std::string,std::allocator<std::string> > *)std_vector_Sl_std_string_Sg____getitem____SWIG_0(arg1,arg2); 
    } 
    catch(std::out_of_range &_e) { 
    SWIG_exception_fail(SWIG_IndexError, (&_e)->what()); 
    } 

    *****1***** 
    ***//I want to modify or print variable result here like printf("%s", result->c_str());*** 

    resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_std__vectorT_std__string_std__allocatorT_std__string_t_t, 0 | 0); 
    return resultobj; 
fail: 
    return NULL; 
} 

我需要打印位置1处的变量的结果(如在代码中提到)。 Typemap(argout)在这里似乎没有多大帮助。

+0

你能显示该函数的原始声明吗?我认为这是你在这里定位的Python? – Flexo 2012-01-17 16:16:40

回答

2

我在这里假设你想要修改的函数是std::vector<std::string>的Python例程__getitem__

修改或拦截返回值的结果,最简单,最安全的方式实际上是做在Python端,使用%feature("pythonappend"),如:

%module test 

%{ 
#include "test.h" 
%} 

%include "pyabc.i" 
%include "std_vector.i" 
%include "std_string.i" 

%feature("pythonappend") std::vector<std::string>::__getitem__ %{ 
    # do something 
    print val 
%} 

%include "test.h" 

%template (StringVector) std::vector<std::string>; 

的原因,这是修改的最简单方法结果是修改结果的下一个最简单的方法需要更改返回类型的类型映射 - 在本例中为std::string。要做到这一点,你最终会改变现有的std::string typemap,这有点混乱。

或者你不妨使用%exception指令把一些C++代码$action后,但除非这是用于验证返回结果的目的,感觉非常的hackish。

+0

非常感谢awoodland,我找到了解决我的问题的办法,但它似乎并不是最优的。我已经在这里解释了解决方案和我的问题[这里](http://stackoverflow.com/questions/8968958/implement-support-for-stdvector-without-std-vector-i)。请看看你是否有时间。谢谢 :-) – Saurabh 2012-01-23 08:54:55