title: Swift: Pass Uninitialized C Structure to Imported C function
body: <p>I'm aware of <a href="https://stackoverflow.com/questions/24090148/c-style-uninitialized-pointer-passing-in-apple-swift">this answer</a>, but this is not the same thing - thats passing a pointer to be initialised with an allocation.</p>
  
  <p>I'm interfacing with a C library that has the following structure definition:</p>
  
  <pre><code>typedef struct myStruct { unsigned char var [50]; } myStruct;
  </code></pre>
  
  <p>There is a function to which you pass the address of the structure - normally stack based not heap, thus:</p>
  
  <pre><code>myStruct mine;
  initMyStruct(&amp;mine);
  </code></pre>
  
  <p>This initialises the content of the struct - the caller does not know the internal format of the memory, hence the obfuscation.</p>
  
  <p>In Swift, I'm creating a class which will encapsulate the structure and interface with other C functions which operates on it.</p>
  
  <pre><code>class MyClass {
  
      var mine : myStruct
  
      init() {
  
          initMyStruct(&amp;mine)
          // Error: Variable 'self.msg' passed by reference before being initialized
  
      }
  
  }
  </code></pre>
  
  <p>I can't for the life of me work out how to initialise the structure, or use a point instead if that is an alternative.</p>
  
  <pre><code>mine = myStruct()
  // Fails because you aren't providing the value of the member 'var'
  
  mine = myStruct((CUnsignedChar(), CUnsignedChar(), /*... repeat to 50 */))
  // Cannot find an overload for 'init' that accepts the arguments
  </code></pre>
  
  <p>Please note, this is passing the address of an already allocated (stack based) structure to a function that has been imported as </p>
  
  <pre><code>CInt initMyStruct(str: CMutablePointer&lt;myStruct&gt;)
  </code></pre>
  
  <p>It is NOT passing a pointer to be allocated by the C library in question which seems to be a more common requirement and is answered elsewhere.</p>
  
  <p>Swift currently doesn't support fixed size arrays either.</p>
  
  <p>I can't see how to satisfy the initialisation of the structure or make Swift think that it is going to be done so by the call.</p>
  
  <p>Any help greatly appreciated!</p>