Python Properties & Swig

后端 未结 6 896
日久生厌
日久生厌 2021-01-30 09:24

I am attempting to create python bindings for some C++ code using swig. I seem have run into a problem trying to create python properties from some accessor functions I have for

6条回答
  •  温柔的废话
    2021-01-30 10:02

    I had the same problem and the advice to use %pythoncode worked for me. Here is what I did:

    class Foo {
      // ...
      std::string get_name();
      bool set_name(const std::string & name);
    };
    

    In the wrapper:

    %include "foo.h"
    %pythoncode %{
    def RaiseExceptionOnFailure(mutator):
      def mutator(self, v):
        if not mutator(self, v):
         raise ValueError("cannot set property")
      return wrapper
    Foo.name = property(Foo.get_name, RaiseExceptionOnFailure(Foo.set_name))
    %}
    

提交回复
热议问题