Question

I have an DLL that has this in its h file:

extern "C" __declspec(dllexport) bool Connect();

and in the c file:

extern "C" __declspec(dllexport) bool Connect()
{
     return false;  
}

In c# i have the following 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);
}

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.

Any ideas?

Was it helpful?

Solution

The problem propably is in the "bool". In MSVC sizeof(bool) is 1 while sizeof(BOOL) is 4! BOOL is the type used by windows API to express a boolean value, and is a 32 bit integer. So C# expets a 32 bit value but u are prividing a 1 byte value, so u are getting "garbage".

There are two solutions:

1) u change your C code to return BOOL or int.

2) You change the C# code adding [return:MarshalAs(UnmanagedType.I1)] attribute to your dll import functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top