标签:dllexport late-binding c-3 c
我有一个在其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中的返回值是什么,connect函数总是返回true.
我尝试将C#中的调用约定更改为StdCall,但问题仍然存在.
有任何想法吗?
解决方法:
问题可能出在“布尔”中.
在MSVC中,sizeof(bool)为1,而sizeof(BOOL)为4!
BOOL是Windows API用于表示布尔值的类型,并且是32位整数.
因此,C#使用32位值,但是u占用1个字节的值,因此u获得“垃圾”.
有两种解决方案:
1)u更改您的C代码以返回BOOL或int.
2)您更改C#代码,将[return:MarshalAs(UnmanagedType.I1)]属性添加到dll导入函数.
标签:dllexport,late-binding,c-3,c 来源: https://codeday.me/bug/20191102/1987911.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。