[C++-sig] wrap union types with boost.python

Stefan Seefeld stefan at seefeld.name
Sun Jan 16 12:46:54 EST 2022


On 2022-01-16 12:29, Malte Dreschert wrote:
> Hi Stefan,
>
> thanks for answering and a greetings from northern Germany to Berlin :)
>
> the struct is meant to hold color values (three floats) but the color 
> space can be different.
> It contains three of these unions and one enum value that contains the 
> information which color space was used when the values were written.
> The floats are either rgb or hsv.
>
> The library is for reading a binary file and I only have these structs 
> and some methods I need to wrap, that means I only need to read the 
> values.
> I guess I would first check the color space and then interpret the 
> three values accordingly.

Right, and I assume you already have a C++ API to access that struct, 
even if it isn't in terms of member functions. As far as the raw data 
type and its binary representation is concerned, there is nothing 
special here, i.e. you could wrap it in a Python object as-is. But what 
you likely want is a set of (member) functions to access the values, and 
that is very likely mapping to your C++ API more than mapping to the 
struct directly.

For example, let's assume you have:

```

struct someStruct {/*...*/};
float get_value(someStruct const &);
void set_value(someStruct &, float);

```

you may decide to map `get_value` and `set_value` to direct methods:

```

class_<someStruct> s("someStruct");
s.def("get_value", get_value);
s.def("set_value", set_value);

```

(Notice how the freestanding functions lend themselves naturally to 
become methods as their first argument is the equivalent of the 
otherwise implied "this" pointer...)

Or you may want to map both directly to a property:

```

class_<someStruct> s("someStruct");
s.add_property("value", get_value, set_value);
```

Either way, there is nothing special in this wrapping concerning the 
fact that your struct contains a union. Rather, it's your C++ API that 
will have to deal with that.

Regards (from Montreal ;-)),

Stefan

-- 

       ...ich hab' noch einen Koffer in Berlin...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/cplusplus-sig/attachments/20220116/e2574566/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: .signature.png
Type: image/png
Size: 2754 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/cplusplus-sig/attachments/20220116/e2574566/attachment.png>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: stefan.vcf
Type: text/vcard
Size: 4 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/cplusplus-sig/attachments/20220116/e2574566/attachment.bin>


More information about the Cplusplus-sig mailing list