标签:函数 C# errCode 错误码 Windows int ref
有时候开发经常会调用Windows自己的函数实现业务功能。这个过程中,底层函数可能会出现错误,返回的错误码类似“0xxxxxxxxxx”这样,不容易具体看到错误的问题。
Windows同样提供了方法对这些错误码进行转义为具体的错误信息描述。以下示例以.NET C#语言实现。
1.工具类
/// <summary>
/// 对需要获取错误信息码的C函数,标签上补充SetLastError = true
/// 获取错误码的方式:int errCode = Marshal.GetLastWin32Error()
/// 获取错误码对应的错误描述信息的方式:string errMsg = GetSysErrMsg(errCode);
/// </summary>
public static class ErrMsgUtils
{
#region 获取C函数错误码对应的错误信息描述
/// <summary>
/// Kernel32.dll下根据错误码获得对应的错误信息描述用方法,不推荐直接调用
/// </summary>
[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
public extern static int FormatMessage(
int flag,
ref IntPtr source,
int msgid,
int langid,
ref string buf,
int size,
ref IntPtr args);
/// <summary>
/// 获取系统错误信息描述
/// </summary>
/// <param name="errCode">系统错误码</param>
/// <returns>错误信息描述</returns>
public static string GetSysErrMsg(int errCode)
{
IntPtr tempPtr = IntPtr.Zero;
string msg = null;
FormatMessage(0x1300, ref tempPtr, errCode, 0, ref msg, 255, ref tempPtr);
return msg;
}
#endregion
}
2.调用方式
using System.Runtime.InteropServices;
if(!CallWindowsFunc(xxx))//假设CallWindowsFunc方法里调用了Windows底层函数,以静态类形式引入Windows函数头,并给函数标注[SetLastError = true]标签,返回true代表执行Windows函数成功,返回false代表执行失败
{
//可以获取操作系统对此种情况的错误码的解析内容描述
int errCode = Marshal.GetLastWin32Error();//获取错误码
string errMsg = ErrMsgUtils.GetSysErrMsg(errCode);//调用工具类获取具体的错误信息内容
}
标签:函数,C#,errCode,错误码,Windows,int,ref 来源: https://www.cnblogs.com/jeff151013/p/16080757.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。