How to apply SWIG OUTPUT typemaps for class types in Python?

后端 未结 3 820
青春惊慌失措
青春惊慌失措 2020-12-17 19:52

I am having some trouble generating a Python wrapper around a C++ library using SWIG (version 3.0.6).

My issue relates to applying the OUTPUT typemap, specifically i

3条回答
  •  萌比男神i
    2020-12-17 20:07

    I think you need to use pointers. I am also not sure what happens, when mixing out typemaps and return statements. A minimal example file tst.i:

    %module tst
    
    %{
    
      // declaration:
      void add(long *resultLong, const long arg1,const long arg2);
      long mul(const long a, const long b);
    
      // the code:
      void add(long *resultLong, const long arg1,const long arg2) {
        *resultLong = arg1 + arg2;
      }
      long mul(const long a, const long b) {
        return a*b;
      }
    
    %}
    
    // The wrapper:
    %apply (long* OUTPUT) { long* resultLong }; 
    void add(long* resultLong, const long arg1,const long arg2);
    long mul(const long a, const long b);
    

    After translating (I always use CMake), the usage in python would be:

    import tst
    x = tst.add(3, 4)  # results in 7L    
    y = tst.mul(3, 4)  # results in 12L
    

    I think it is better using return statements instead of typemaps for scalar datatypes. When interfacing arrays, I recommend using the predefined typemaps of numpy.i.

提交回复
热议问题