title: How can I pass a variable-length string from an RPC server to the client?
body: <p>I am implementing a Windows system service, which acts as RPC server, and a corresponding client, both in C++. I am using plain Windows RPC functionality.</p>
  
  <p>Passing strings from the RPC client to the server is easy. Just declare the function parameter in the IDL file like this:</p>
  
  <pre><code>[in, string] wchar_t* myString
  </code></pre>
  
  <p>MIDL will take care of the memory-allocation magic. Works like a treat.</p>
  
  <p>Returning a modified client string is also easy:</p>
  
  <pre><code>[in, out, string] wchar_t* myString
  </code></pre>
  
  <p>That requires me to properly size the string on the client side, though.</p>
  
  <p><strong>Problem:</strong></p>
  
  <p>I need to return strings from the server to the client. I do not know on the client how large they are going to be, so memory allocation on the client is not an option.</p>
  
  <p>I <em>could</em> allocate a very large amount of memory, say 10K, an amount large enough for every string the server could possibly return. But that is a huge waste of resources (memory, network), and I still cannot know for certain that the server never needs to return a larger string.</p>
  
  <p><strong>What I tried:</strong></p>
  
  <p>Amonst many other things I tried the technique used in Microsoft's <a href="http://msdn.microsoft.com/en-us/library/aa373823%28VS.85%29.aspx" rel="noreferrer">strout</a> sample. It worked when calling the RPC function for the first time, but crashed the server when called for the second time.</p>