我有使用反射等从 C# 调用的 C++ 代码。
我遇到的奇怪的事情是在 C++ 端函数声明看起来像这样
dppFUNC(HRESULT) dppOnlineGetBalanceInfo(
在 C# 端它被声明为
[DllImport("dppClientModule.dll", CallingConvention = CallingConvention.StdCall)]
private static extern UInt32 dppOnlineGetBalanceInfo(
为什么C#代码的返回类型是uint
?不应该是int
吗?
它会导致什么问题?现在已经这样使用了,请问会造成什么问题?
重复的链接问题似乎有所不同,因为接受的答案中 MAKEHRESULT(C# 版本)的结果是 int,为什么?
最佳答案
HRESULT
在 C/C++ 中被定义为 long(32 位有符号)。所以从技术上讲,在 C# 中,您将使用 int
。这也是 Microsoft 自己在 C# 中用于 Exception.HResult 的类型.
在 uint
上使用 int
的缺点是你必须显式转换,同时禁用溢出检查( unchecked
),所有列出的常量MSDN documentation :
例如:
const int E_FAIL = 0x80004005;
Cannot implicitly convert type 'uint' to 'int'. An explicit conversion exists (are you missing a cast?)
添加显式转换:
const int E_FAIL = (int)0x80004005;
Constant value '2147500037' cannot be converted to a 'int' (use 'unchecked' syntax to override)
现在,您有三个选择:
const int E_FAIL = -2147467259;
const int E_FAIL = unchecked((int)0x80004005);
const uint E_FAIL = 0x80004005;
使用负值无助于提高可读性。因此,要么将所有常量定义为 unchecked((int)...)
,要么将 HRESULT
视为 uint
。
关于c# - C++和C#之间HRESULT的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34198173/