4

我有一个 DLL,它的 h 文件中有这个:

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

在c文件中:

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

在 c# 中,我有以下代码:

[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);
}

出于某种奇怪的原因,无论 C++ 中的返回值是什么,connect 函数总是返回 true。我尝试在 C# 中将调用约定更改为 StdCall,但问题仍然存在。

有任何想法吗?

4

1 回答 1

5

问题可能出在“布尔”中。在 MSVC 中 sizeof(bool) 为 1 而 sizeof(BOOL) 为 4!BOOL 是 windows API 用来表示布尔值的类型,是一个 32 位整数。所以 C# expets 一个 32 位的值,但你正在使用一个 1 字节的值,所以你得到了“垃圾”。

有两种解决方案:

1)你改变你的C代码返回BOOL或int。

2)您将 C# 代码添加[return:MarshalAs(UnmanagedType.I1)]属性更改为您的 dll 导入函数。

于 2011-11-20T16:07:35.880 回答