Using crystal with a C struct of undetermined size

I’m brand new to Crystal. So far I really like what I see. I’ve been experimenting with Crystal’s ability to work with C code. One thing I haven’t been able to figure out so far is what the best way is to work with a C struct with a definition similar to this:

struct string_t {
  unsigned char n;
  char characters[]; 
};           

where n is the length of character data in the characters array.

I’m getting a pointer to a struct of string_t from a file, so the format is already defined, and the data is already populated.

I’ve tried this:

@[Extern]
struct ShortString
  @n = uninitialized UInt8
  @characters = uninitialized UInt8[0]
  getter :n
  def characters
    String.new(pointerof(@characters).as(UInt8*), @n)
  end
end

I feel like I’m close, but it doesn’t seem to do what I want. The value for @n seems to be populated correctly. However, the way I’m handling characters must be incorrect, as I’m not seeing the data I’d expect, but I haven’t been able to come up with an alternate formulation that seems to make sense and the compiler is ok with.

Any suggestions for the correct way to handle this?

Binding to C flexible array members · Issue #10598 · crystal-lang/crystal · GitHub might help.

this is perfect, thank you for the link!