2011-11-20 63 views
3

我有了这个在其H文件中的DLL:后期绑定C++ DLL到C# - 功能总是返回true

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

这个问题显然是在“布尔”。 在MSVC sizeof(布尔)是1,而sizeof(布尔)是4! BOOL是由windows API用来表示布尔值的类型,并且是一个32位整数。 所以C#发挥了32位的价值,但你是一个1字节的价值,所以你变得“垃圾”。

解决办法有两个:

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

2)您更改C#代码添加[return:MarshalAs(UnmanagedType.I1)]属性到您的dll导入功能。

+0

这样做。谢谢! – Nitay