title: How do I convert a cdata structure into a lua string?
body: <p>I'm in the middle of writing a small application that needs to read some complex binary messages in LuaJit.</p>
  
  <p>I've been using the bit module and string.rep a lot.  However, it's all very cumbersome.  I'm new to using LuaJit and think there might be a much easier way using FFI.</p>
  
  <p>In C I can declare a structure like this:</p>
  
  <pre><code>struct mystruct
  {
    uint32_t field1;
    char     field2[6];
    uin64_t  field3;
    short    field4;
  } __attribute__(packed);
  </code></pre>
  
  <p>In reading LuaJit's FFI it seems you can declare </p>
  
  <pre><code>ffi.cdef[[
      #pragma pack(1)
      struct mystruct
      {
        uint32_t field1;
        char     field2[6];
        uin64_t  field3;
        short    field4;
      };
  ]]
  </code></pre>
  
  <p>I can then create a mystruct and access the fields like this:</p>
  
  <pre><code>local ms = ffi.new("mystruct")
  ms.field1 = 32;
  // ... etc
  </code></pre>
  
  <p>But, how do I convert this back into a lua string?</p>
  
  <p>I tried this, but it didn't seem to do what I wanted.</p>
  
  <pre><code>local s = tostring(ms)
  </code></pre>
  
  <p>and this:</p>
  
  <pre><code>local s = ffi.string(ms)
  </code></pre>
  
  <p>produces the following error "bad argument #1 to 'string' (cannot convert 'struct mystruct' to 'const char *')"</p>
  
  <p>So I tried a cast:</p>
  
  <pre><code>local s = ffi.string(ffi.cast("char*", ms))
  </code></pre>
  
  <p>No error, but it looks wrong on the wire.</p>