我有使用反射等从 C# 调用的 C++ 代码。
我遇到的奇怪的事情是 C++ 端函数声明看起来像这样
dppFUNC(HRESULT) dppOnlineGetBalanceInfo(
Run Code Online (Sandbox Code Playgroud)
在 C# 方面,它被声明为
[DllImport("dppClientModule.dll", CallingConvention = CallingConvention.StdCall)]
private static extern UInt32 dppOnlineGetBalanceInfo(
Run Code Online (Sandbox Code Playgroud)
为什么是 C# 代码的返回类型uint?不应该int吗?
它会导致什么问题?现在都这样用了,想知道会导致什么问题?
作为重复的链接问题似乎不同,因为在接受的答案中 MAKEHRESULT(C# 版本)的结果是 int,为什么?
HRESULT在 C/C++ 中定义为 long(32 位有符号)。因此,从技术上讲,在 C# 中,您将使用int. 这也是微软自己在 C# 中用于Exception.HResult 的类型。
使用intover的缺点uint是,您必须在禁用溢出检查 ( unchecked) 的同时显式转换MSDN 文档中列出的所有常量:
例如:
const int E_FAIL = 0x80004005;
Run Code Online (Sandbox Code Playgroud)
无法将类型“uint”隐式转换为“int”。存在显式转换(您是否缺少演员表?)
添加显式演员表:
const int E_FAIL = (int)0x80004005;
Run Code Online (Sandbox Code Playgroud)
常量值“2147500037”无法转换为“int”(使用“unchecked”语法覆盖)
现在,您有三个选择:
const int E_FAIL = ?-2147467259?;
const int E_FAIL = unchecked((int)0x80004005);
const uint E_FAIL = 0x80004005;
Run Code Online (Sandbox Code Playgroud)
使用负值无助于使事情更具可读性。因此,要么将所有常量定义为unchecked((int)...)或HRESULT视为uint。