windows下如何将FormatMessage输出转换为JNI中的Java异常消息?
我正在尝试使用以下功能将 Windows 错误转换为 java IOException:
void ThrowIOException(JNIEnv * env, LPCTSTR lpszFunction, DWORD dw)
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
// MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LPVOID lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
jclass Exception = env->FindClass("java/io/IOException");
if(env->ThrowNew(Exception, (const char *)lpDisplayBuf)){
printf("Can't throw IOException: %s\n", lpDisplayBuf);
}
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
我在 VC 项目中使用 Unicode。 IOException 成功抛出,但 'lpDisplayBuf' 中的消息未正确显示。
我知道将 lpDisplayBuf 转换为“const char *”可能是错误的,但我不知道如何纠正它。
I am trying to convert Windows error to an java IOException with the fuciont below:
void ThrowIOException(JNIEnv * env, LPCTSTR lpszFunction, DWORD dw)
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
// MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LPVOID lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
jclass Exception = env->FindClass("java/io/IOException");
if(env->ThrowNew(Exception, (const char *)lpDisplayBuf)){
printf("Can't throw IOException: %s\n", lpDisplayBuf);
}
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
I am using Unicode in my VC project. The IOException throws successfully, but the message in 'lpDisplayBuf' is not displayed properly.
I am aware of that casting lpDisplayBuf to "const char *" might be wrong, but I don't know how to correct it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的 VC 项目设置为 UNICODE,那么您需要将从 FormatMessage 返回的字符串转换为 ANSI,如下例所示(请注意,我根本没有进行错误检查)
希望这会有所帮助。
If your VC project is setup as UNICODE then you need to convert the string returned from FormatMessage to ANSI as in the following example (please, note that I put no error checking at all)
Hope this helps.