title: Late Binding C++ DLL to C# - Function always returns true
body: <p>I have an DLL that has this in its h file:</p>
  
  <pre><code>extern "C" __declspec(dllexport) bool Connect();
  </code></pre>
  
  <p>and in the c file:</p>
  
  <pre><code>extern "C" __declspec(dllexport) bool Connect()
  {
       return false;  
  }
  </code></pre>
  
  <p>In c# i have the following code:</p>
  
  <pre><code>[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  private delegate bool ConnectDelegate();
  
  private ConnectDelegate DLLConnect;
  
  public bool Connect()
  {
      bool l_bResult = DLLConnect();
      return l_bResult;
  }
  
  public bool LoadPlugin(string a_sFilename)
  {
     string l_sDLLPath = AppDomain.CurrentDomain.BaseDirectory;
  
     m_pDLLHandle = LoadLibrary(a_sFilename);
     DLLConnect = (ConnectDelegate)GetDelegate("Connect", typeof(ConnectDelegate));
     return false;
  }
  
  private Delegate GetDelegate(string a_sProcName, Type a_oDelegateType) 
  {
      IntPtr l_ProcAddress = GetProcAddress(m_pDLLHandle, a_sProcName);
      if (l_ProcAddress == IntPtr.Zero)
         throw new EntryPointNotFoundException("Function: " + a_sProcName);
  
      return Marshal.GetDelegateForFunctionPointer(l_ProcAddress, a_oDelegateType);
  }
  </code></pre>
  
  <p>For some weird reason the connect function always returns true no matter what the return value is in the C++. 
  I've tried changing the calling convention to StdCall in C#, but the problem stays.</p>
  
  <p>Any ideas?</p>