title: C++ 'substitute' for structure with a flexible array member
body: <p>Consider the following C99 structure, ending with a flexible array member:</p>
  
  <pre><code>struct hdr
  {
    size_t len;   
    size_t free;  
    char buf[];
  };
  </code></pre>
  
  <p><code>len</code>, for example, gets accessed with an inline function (to be put into a header file) like this, having <code>buf</code> as its argument:</p>
  
  <pre><code>static inline size_t slen(const char *s)
  {
    struct hdr *h = (struct hdr*)(s - (int)offsetof(struct hdr, buf));
    return h-&gt;len;
  }
  </code></pre>
  
  <p>This is part of a library, to be compiled with a C compiler.  However, I would like to access this library from C++; this essentially means that the corresponding header file (with proper <code>extern "C" {...}</code> guard) must be valid C++ code.  A possible solution is to define the <code>slen</code> function in the source code body, avoiding inline code completely, but this is not optimal.</p>
  
  <p>My idea is to define a dummy C++ structure that is valid, and that I can map somehow to <code>hdr</code>, e.g.</p>
  
  <pre><code>struct cpp_hdr
  {
    size_t len;
    size_t free;
    char buf[1];
  }
  </code></pre>
  
  <p>Note that I only want to get correct (negative) offset values for <code>len</code> and <code>free</code>; no access to <code>buf</code> is intended.</p>
  
  <p>Now my question: Is there any guarantee that</p>
  
  <pre><code>static inline size_t slen(const char *s)
  {
    struct cpp_hdr *h = (struct cpp_hdr*)(s - (int)offsetof(struct cpp_hdr, buf));
    return h-&gt;len;
  }
  </code></pre>
  
  <p>works, giving the same result?  </p>