4

私はそのhファイルにこれを持っているDLLを持っています:

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

1 に答える 1

5

問題はおそらく「ブール」にあります。MSVCでは、sizeof(bool)は1ですが、sizeof(BOOL)は4です。BOOLは、Windows APIがブール値を表すために使用する型であり、32ビット整数です。したがって、C#は32ビット値を出力しますが、uは1バイト値を提供しているため、uは「ガベージ」を取得しています。

2つの解決策があります:

1)u Cコードを変更して、BOOLまたはintを返します。

[return:MarshalAs(UnmanagedType.I1)]2) dllインポート関数のC#コード追加属性を変更します。

于 2011-11-20T16:07:35.880 に答える