Skip to content Skip to sidebar Skip to footer

How To Handle A Union In Python-sip?

I'm using SIP version 5.4.0 and have no trouble translating a struct in c++ for python3.8. When I want to translate a union sip-install gives me a syntax error. Any ideas? Thank yo

Solution 1:

The Trick is to wrap it in a struct and use %GetCode and %SetCode for each union element. The following example should make things clear:

The following header file:

uniontest_u {
    char test1;
    int test2;
    double test3;
};

is translated with this SIP file:

struct union_wrapper /PyName=test_u/
{

%TypeHeaderCode
#include<test_union.h>

struct union_wrapper
{
    union test_u wrapped_u;
};
%End

    char test1 {
    %GetCode
        sipPy = PyUnicode_FromString(&(sipCpp->wrapped_u.test1));
    %End
    %SetCode
        if (PyUnicode_Check(sipPy))
            sipCpp->wrapped_u.test1;
        else
            sipErr = 1;
    %End
    };

    int test2 {
    %GetCode
        sipPy = PyLong_FromLong(sipCpp->wrapped_u.test2);
    %End
    %SetCode
        if (PyLong_Check(sipPy))
            sipCpp->wrapped_u.test2;
        else
            sipErr = 1;
    %End
    };

    double test3 {
    %GetCode
        sipPy = PyFloat_FromDouble(sipCpp->wrapped_u.test3);
    %End
    %SetCode
        if (PyFloat_Check(sipPy))
            sipCpp->wrapped_u.test3;
        else
            sipErr = 1;
    %End
    };
};

This solution is not my achievement, but I don't know if I can name names. Thank you very much!

Johnny Walker

Post a Comment for "How To Handle A Union In Python-sip?"