title: Return data from native method via pointer in .NET
body: <p>The function I'm calling is part of an obscure API that cannot be PInvoked because the library's only entry point is a structure of pointers to the functions within. That being said, I have the structure and C++ implementation sample code. </p>
  
  <blockquote>
    <p>tl;dr I'm not PInvoking this function.</p>
  </blockquote>
  
  <p>Here is what the implementation looks like in C++</p>
  
  
  
  <pre class="lang-cpp prettyprint-override"><code>// Definition
  extern  "C"  typedef short  (* GETBIT)(short,char*);
  
  // Base function for using API
  void anApi::GetData(short index, void* pData)
  {
      switch(internal logic...)
      {
          case bitData:
              get_bit(index, (char *)(pData));
  
          case (other data types)...
      }
  }
  
  // Higher level API implementation
  UCHAR u1Val = 0;
  GetData( 1234, &amp;u1Val );
  
  if( u1Val == 1 )
  {
      doSomthing();
  }
  </code></pre>
  
  <p>Presumably I should get back either 0 or 1 (even with the actual data type being what it is). I should mention that the API has error checking, which I left out for simplicity sake, and my code does not cause any error. There is also an initialization function which succeeds, so I know I'm calling the functions correctly.</p>
  
  <p>Here is how I've implemented the same function in C#</p>
  
  
  
  <pre class="lang-c# prettyprint-override"><code>// Definition
  [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  delegate short get_bit_delegate(short index, out byte data);
  get_bit_delegate get_bit; 
  
  // Base function
  public string GetDataBit(short index)
  {
      string ReturnData = "test";       
      // Using .NET type of Byte instead of char...
      byte myByte = 0;              
      lRetCode = get_bit(index, out myByte);
      // get a good look at what we returned
      ReturnData = Convert.ToString(myByte, 2).PadLeft(8, '0');
      return ReturnData;
      // error checking snipped for brevity 
  }
  
  // Implementation
   textBox1.Text = GetDataBit(1234);
  </code></pre>
  
  <p>I've tried different data types including IntPtr and then Marshaling, but I keep getting the same result: </p>
  
  <blockquote>
    <p>11111111 ( ÿ )</p>
  </blockquote>
  
  <p>The way they use the result in the sample code, I would think that the return value should be '1' or '0'. In fact, in my test case I'm expecting to see 0.</p>
  
  <p>0 - chr(48) - 00110000<br>
  1 - chr(49) - 00110001</p>