python-3.xcythonopenal-soft

How to write #define expressions with nested brackets in cython?


C expression:

#define EFX_REVERB_PRESET_GENERIC \
    { 1.0000f, 1.0000f, 0.3162f, 0.8913f, 1.0000f, 1.4900f, 0.8300f, 1.0000f, 0.0500f, 0.0070f, { 0.0000f, 0.0000f, 0.0000f }, 1.2589f, 0.0110f, { 0.0000f, 0.0000f, 0.0000f }, 0.2500f, 0.0000f, 0.2500f, 0.0000f, 0.9943f, 5000.0000f, 250.0000f, 0.0000f, 0x1 }

I want to define this expression in the .pxd file.

I have to pass this expression as parameters to some C functions. So I don't use it for Python.

Source: OpenAL-Soft: https://github.com/kcat/openal-soft/blob/master/include/AL/efx-presets.h#L37


Solution

  • It's worth realising that not everything has a direct translation from C to Cython. In this case EFX_REVERB_PRESET_GENERIC can't really be defined using a type because it isn't a type - it's just a collection of brackets and numbers. These brackets and numbers are only valid in a small number of places:

     void other_func(WhateverTheStructIsCalled s);
    
     void func() {
         WhateverTheStructIsCalled s = EFX_REVERB_PRESET_GENERIC; // OK
         s = EFX_REVERB_PRESET_GENERIC; // wrong - not an initialization
         other_func(EFX_REVERB_PRESET_GENERIC); // also doesn't work
     }
    

    Therefore it doesn't really fit into Cython's model so you can't wrap it directly.

    What I'd do is write a small C wrapper yourself. You can do this with Cython's "inline C code" function:

    cdef extern from *:
        """
        WhateverTheStructIsCalled get_EFX_REVERB_PRESET_GENERIC(void) {
            WhateverTheStructIsCalled s = EFX_REVERB_PRESET_GENERIC;
            return s;
        }
        """
        WhateverTheStructIsCalled get_EFX_REVERB_PRESET_GENERIC()
    

    Then use get_EFX_REVERB_PRESET_GENERIC() to call this function and get the relevant initialized structure.