%typemapping of a C++ Library for Python Interface

前端 未结 2 410
不知归路
不知归路 2021-01-22 19:00

I want to create a python wrapper for my C++ library. It would be cool, if there is a automatic conversion of std::vector to python lists and the other way round. Unfortunatly

相关标签:
2条回答
  • 2021-01-22 19:35

    If you're going to define the %typemaps manually, you will also need a %typemap(check), something like:

    %typemap(typecheck) std::vector<float>& {
        $1 = PySequence_Check($input) ? 1 : 0;
    }
    

    I believe the rule of thumb is that if you define a %typemap(in), you should also define a %typemap(check) --- otherwise, the generated code never gets to where it's put your %typemap(in).

    0 讨论(0)
  • 2021-01-22 19:37

    The std_vector.i library in SWIG provides support for std::vector.

    http://www.swig.org/Doc2.0/Library.html#Library_stl_cpp_library

    You just need to tell SWIG about the template instantiations you want it to know about:

    %include "std_vector.i"
    
    namespace std {
        %template(FloatVector) vector<float>;
    }
    

    Note that the following Python code will work, but will incur an array copy:

    for x in range(0, 3):
        list[x] = x
    myModule.myFunction(list)
    

    To do the same thing without incurring a copy, construct the list using the SWIG-generated proxy object constructor:

    list = myModule.FloatVector()
    for x in range(0, 3):
        list[x] = x
    myModule.myFunction(list)
    
    0 讨论(0)
提交回复
热议问题