Search code examples
crystal-lang

How to have an array type in C binding?


I'm trying to port this code :

struct SoundIoChannelLayout {
    const char *name;
    int channel_count;
    enum SoundIoChannelId channels[SOUNDIO_MAX_CHANNELS];
};

But i don't know how to define the type of channels, and I know that I can't use a pointer because the final struct size won't be the same.


Solution

  • I was able to auto-generate it using crystal_lib:

    $ cd crystal_lib
    $ cat examples/soundio.cr
    @[Include("soundio/soundio.h", prefix: %w(SoundIo))]
    @[Link("soundio")]
    lib LibSoundio
    end
    $ crystal src/main.cr -- examples/soundio.cr > soundio.cr
    

    So it looks like this:

    @[Link("soundio")]
    lib LibSoundio
      MAX_CHANNELS = 24
    
      struct ChannelLayout
        name : LibC::Char*
        channel_count : LibC::Int
        channels : ChannelId[MAX_CHANNELS]
      end
    
      enum ChannelId
        Invalid = 0
        FrontLeft = 1
        FrontRight = 2
        FrontCenter = 3
        # ...
      end
      # ...
    end
    

    Note: you may need to update resulted file manually because crystal_lib is still experimental.