title: Getting at C binary data from OCaml
body: <p>(Ignoring endianness for the sake of argument - this is just a test case/proof of concept - and I would never use <code>strcpy</code> in real code either!)</p>
  
  <p>Consider the following trivial C code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  /* variables of type message_t will be stored contiguously in memory */
  typedef struct {
    int message_id;
    char message_text[80];
  } message_t;
  
  int main(int argc, char**argv) {
    message_t* m = (message_t*)malloc(sizeof(message_t));
    m-&gt;message_id = 1;
    strcpy(m-&gt;message_text,"the rain in spain falls mainly on the plain");
  
    /* write the memory to disk */
    FILE* fp = fopen("data.dat", "wb");
    fwrite((void*)m, sizeof(int) + strlen(m-&gt;message_text) + 1, 1, fp);
    fclose(fp);
  
    exit(EXIT_SUCCESS);
  }
  </code></pre>
  
  <p>The file it writes can easily be read back in from disk:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  typedef struct {
    int message_id;
    char message_text[80];
  } message_t;
  
  int main(int argc, char**argv) {
    message_t* m = (message_t*)malloc(sizeof(message_t));
  
    FILE* fp = fopen("data.dat", "rb");
    fread((void*)m, sizeof(message_t), 1, fp);
    fclose(fp);
  
    /* block of memory has structure "overlaid" onto it */
    printf("message_id=%d, message_text='%s'\n", m-&gt;message_id, m-&gt;message_text);
  
    exit(EXIT_SUCCESS);
  }
  </code></pre>
  
  <p>E.g.</p>
  
  <pre><code>$ ./write 
  $ ./read 
  message_id=1, message_text='the rain in spain falls mainly on the plain'
  </code></pre>
  
  <p>My question is, in OCaml, if all I have is:</p>
  
  <pre><code>type message_t = {message_id:int; message_text:string}
  </code></pre>
  
  <p>How would I get at that data? <code>Marshal</code> can't do it, nor can <code>input_binary_int</code>. I can call out to helper functions in C like "what is <code>sizeof(int)</code>" then get n bytes and call a C function to "convert these bytes into an int" for example but in this case I can't add any new C code, the "unpacking" has to be done in OCaml, based on what I know it "should" be. Is it just a matter of iterating over the string either in blocks of <code>sizeof</code>s or looking for '\0' or is there a clever way? Thanks!</p>