这个简短的C ++程序表现得让我困惑:
HANDLE hStdErrRd = NULL;
HANDLE hStdErrWr = NULL;
SECURITY_ATTRIBUTES saAttr = {0};
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if (!CreatePipe(&hStdErrRd, &hStdErrWr, &saAttr, 0)) {
// error handling
}
if (!SetHandleInformation(hStdErrRd, HANDLE_FLAG_INHERIT, 0)) {
// error handling
}
String CmdLine = "\"C:\\path to\\java.exe\" -jar \"C:\\path to\\decompile.jar\" -o Source/ \"C:\\path to\\file.jar\"";
STARTUPINFO si = {0};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError = hStdErrWr;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi = {0};
if (CreateProcess(NULL, CmdLine.c_str(), NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
{
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
// must close our handle to the write-side of the pipe so the pipe will close
// when the child process terminates so ReadFile() will know to stop expecting data...
CloseHandle(hStdErrWr);
AnsiString output;
char buffer[1024];
DWORD dwBytesRead;
while (ReadFile(hStdErrRd, buffer, sizeof(buffer), &dwBytesRead, NULL))
{
if (dwNumRead == 0)
break;
output += AnsiString(buffer, dwBytesRead);
do
{
int pos = output.Pos("\n");
if (pos == 0)
break;
Memo1->Lines->Add(output.SubString(1, pos-1).TrimRight());
output.Delete(1, pos);
}
while (!output.IsEmpty());
}
if (!output.IsEmpty())
Memo1->Lines->Add(output.TrimRight());
}
else
{
// error handling
CloseHandle(hStdErrWr);
}
CloseHandle(hStdErrRd);
使用#include <cassert>
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
int main(void) {
signed char c = -2;
assert(c == -2);
c = boost::lexical_cast<signed char>(std::string("-2"));
std::cout << c << "\n";
}
和g++ 5.2.1
,我得到:
在抛出'boost :: exception_detail :: clone_impl&gt;'的实例后终止调用 what():错误的词法转换:源类型值无法解释为目标
为什么不能将字符串“-2”中的强制转换为boost-1.58.0
,因为此类型可以表示值signed char
?
答案 0 :(得分:3)
解决方案是使用Boost:
#include <boost/lexical_cast.hpp>
#include <boost/numeric/conversion/cast.hpp>
int tmp = boost::lexical_cast<int>(std::string("-2"));
char c = boost::numeric_cast<signed char>(tmp);