2011-11-20 4 views
3

I가 그 시간 파일이이있는 DLL :늦은 바인딩 C++ DLL은 - 함수는 항상 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++에 상관없이 항상 true를 반환합니다. C#에서 호출 규칙을 StdCall로 변경하려고 시도했지만 문제가 계속 발생합니다.

아이디어가 있으십니까?

답변

4

문제는 propably은 "부울"입니다. MSVC에서 sizeof (bool)는 1이지만 sizeof (BOOL)는 4입니다! BOOL은 Windows API에서 부울 값을 표현하는 데 사용되는 유형이며 32 비트 정수입니다. 그래서 C#은 32 비트 값을 가져 오지만 u는 1 바이트 값을 지정하므로 "쓰레기"가 발생합니다. 유 BOOL 또는 INT를 반환하는 C 코드를 변경

1) :

는 두 가지 해결책이 있습니다.

2) 당신은 당신의 DLL 가져 오기 기능에 [return:MarshalAs(UnmanagedType.I1)] 속성을 추가 C# 코드를 변경합니다.

을했다
+0

. 감사! – Nitay