我正在尝试打开一个内存流以与 xmllite 库一起使用。给一个人写信没问题,但是从一个人读信让我很难过。下面是我正在使用的代码。基本上我创建了一个默认的 xml 字符串 (LPWSTR) 并使用 CreateStreamOnHGlobal 将其写入内存流。然后,我从头开始并读回它以确保它在那里(它是)。然后我再次寻找并将其分配给读者的输入。它永远不会越界:
while (S_OK == (hr = pReader->Read(&nodeType)))
我得到一个 XmlNodeType_None 和一个 HRESULT 值 -1072894427。我相信它无法读取流,但我不确定。如果我改用文件流并从内存流写入 xml,则相同的代码也可以正常工作
HRESULT hr = S_OK; CComPtr<IStream> pStream = NULL;
IXmlReader *pReader = NULL;
XmlNodeType nodeType;
LPWSTR pwszXMLString =
L"<?xml version\"1.0\" encoding=\"UTF-8\" ?>\r\n"
L"<paramlist name=\"LP\">\r\n"
L"<value></value>\r\n"
L"<value></value>\r\n"
L"</paramlist>\r\n"
L"<param name=\"AutoConnect\">false</param>\r\n"
L"<param name=\"ConnectWhenLit\">false</param>\r\n"
L"<param name=\"SessionMaxBytes\">200000</param>\r\n"
L"<param name=\"SessionTimeoutSecs\">300</param>\r\n"
L"<param name=\"PacketDelayMs\">0</param>\r\n"
L"<param name=\"PacketSizeBytes\">4096</param>\r\n"
L"<param name=\"LowSSLSecurity\">true</param>\r\n";
DWORD dwWritten = 0;
hr = CreateStreamOnHGlobal(NULL, FALSE, &pStream);
hr = pStream->Write(pwszXMLString, wcslen(pwszXMLString) * sizeof(WCHAR), &dwWritten);
// print out the contents of the memory stream just to make sure we have it
LARGE_INTEGER pos;
pos.QuadPart = 0;
pStream->Seek(pos, STREAM_SEEK_SET, NULL);
STATSTG ssStreamData = {0};
pStream->Stat(&ssStreamData, STATFLAG_NONAME);
SIZE_T cbSize = ssStreamData.cbSize.LowPart;
LPWSTR pwszContent = (WCHAR*) new BYTE[cbSize + sizeof(WCHAR)];
if (pwszContent == NULL)
return E_OUTOFMEMORY;
pStream->Seek(pos, STREAM_SEEK_SET, NULL);
SIZE_T cbRead;
pStream->Read(pwszContent, cbSize, &cbRead);
pwszContent[cbSize/sizeof(WCHAR)] = L'\0';
CZString czContent;
czContent.LoadWideString(pwszContent, cbSize);
wprintf(L"%S", czContent.GetString().c_str());
pStream->Seek(pos, STREAM_SEEK_SET, NULL);
if (hr == S_OK)
{
typedef HRESULT (WINAPI *CreateXmlReaderFunc)(const IID & riid, void** ppvObject, IMalloc * pMalloc);
CreateXmlReaderFunc _CreateXmlReaderFunc = (CreateXmlReaderFunc)GetProcAddress(m_hXMLLite, "CreateXmlReader");
if (FAILED(hr = _CreateXmlReaderFunc(__uuidof(IXmlReader), (void**) &pReader, NULL)))
{
MessageBox(NULL, CStringHelper::Format(L"Error: GetProcAddress() failed to find 'CreateXmlReader' %d\n", GetLastError()).c_str(), L"Error", MB_OK);
return -1;
}
pReader->SetInput(pStream);
}
while (S_OK == (hr = pReader->Read(&nodeType)))
{
switch (nodeType)
{
// parse xml here
}
}
return 0;