S ++ class wrapped in SIP, fixed in Python

I am creating a Python wrapper over some C ++ library that implements some low-level M2M communication. I use the Riverbank SIP wrapper generator.

The C ++ class has a method:

class Bar {
public:
    enum Status {
        ...
    };
    void setStatus(Status s);
    Status getStatus() const;
    ...
};

The class is contained in the module foo.

SIP uses its own enumeration type, but for several reasons, I would like to use the Python 3.4 enumeration from the standard libray.

I see no chance of accessing classes defined from Python from the Python C API, and I decided to fix the wrapped class in __init__.py. The main reason is because I want to do the dirty work at the low level in C / C ++ / SIP and polish the class in Python (for example, add argument checking using error messages).

Python __init__.py ( ):

from foo import Bar

class Status(IntEnum):
    ONE = 1
    TWO = 2
    ... and so on ...
Status.__module__ = 'Bar.Status'
Bar.Status = Status
Bar.status = property(...)

Bar.status , pythonic Bar.status enum.

:

class Bar(object):
    class Status(IntEnum):
         ...
    ...

, - , .

+4
1

-, .

++, :

  • Foo
  • FooFactory

Wrapper libfoo ( API Python C) pythonic package foo ( python). libfoo, foo.

foo __init__.py:

from libfoo import Foo, FooFactory

# both are naked wrappers with ugly API derived from C++
# I defined some pythonic sugar that makes them nice to use

class FooPythonicGoodies(object):
    # add pythonic goodies here
    def quack(self):
        pass

# Merge them
Foo.__bases__ = Foo.__bases__ + (FooPythonicGoodies,)

, - :

from foo import Foo, FooFactory

a = Foo()
a.quack()

# Factory is a C++ wrapped class that returns wrapped foo
# objects WITH FooPythonicGoodies!
factory = FooFactory()
b = factory.create_foo()
b.quack() # that works too!

, - ++ API- pythonic.

+1

Source: https://habr.com/ru/post/1539187/


All Articles