Может кто помочь где ошибка преобразования? Чет никак не пойму)
C++:
#include <windows.h>
#include <mshtml.h>
#include <shlwapi.h>
#pragma comment(lib, "urlmon.lib")
#pragma comment(lib, "shlwapi.lib")
// Функция для создания SAFEARRAY с BSTR
SAFEARRAY* CreateBstrArray(LPCWSTR str)
{
SAFEARRAY* sa = SafeArrayCreateVector(VT_BSTR, 0, 1);
if (sa) {
LONG index = 0;
BSTR bstr = SysAllocString(str);
SafeArrayPutElement(sa, &index, bstr);
SysFreeString(bstr);
}
return sa;
}
static void WriteHT(IHTMLDocument2* doc, const LPCWSTR content, const LPCWSTR baseURL)
{
if (baseURL && wcslen(baseURL) > 0) {
HRESULT hr;
IStream* stream = ::SHCreateMemStream((BYTE*)(content), (DWORD)(wcslen(content) * sizeof(WCHAR)));
if (stream) {
IPersistMoniker* persistMoniker = NULL;
hr = doc->QueryInterface(IID_IPersistMoniker, (void**)(&persistMoniker));
if (hr == S_OK) {
IBindCtx* ctx = NULL;
hr = ::CreateBindCtx(0, &ctx);
if (hr == S_OK) {
IMoniker* moniker = NULL;
hr = ::CreateURLMoniker(NULL, baseURL, &moniker);
if (hr == S_OK) {
hr = persistMoniker->Load(TRUE, moniker, ctx, STGM_READ);
moniker->Release();
}
ctx->Release();
}
persistMoniker->Release();
}
stream->Release();
}
}
else {
SAFEARRAY* sa = CreateBstrArray(content);
if (sa) {
doc->write(sa);
IHTMLElementCollection* pCollection = NULL;
HRESULT hr{};
hr = doc->get_all(&pCollection);
if (SUCCEEDED(hr)) {
// Теперь вы можете работать с коллекцией элементов
// Например, перебрать все элементы <p> в документе
long itemCount = 0;
hr = pCollection->get_length(&itemCount);
if (SUCCEEDED(hr)) {
for (long i = 0; i < itemCount; i++) {
IDispatch* pDisp = NULL;
VARIANT varName;
VariantInit(&varName);
varName.vt = VT_I4;
varName.lVal = i;
VARIANT varIndex;
VariantInit(&varIndex);
varIndex.vt = VT_EMPTY; // You can specify the appropriate value for 'name' if needed.
hr = pCollection->item(varName, varIndex, &pDisp);
if (SUCCEEDED(hr)) {
// Check if the returned pDisp is not null
if (pDisp) {
// Now you can work with the pDisp as needed
IHTMLElement* pElement = NULL;
hr = pDisp->QueryInterface(IID_IHTMLElement, (void**)&pElement);
if (SUCCEEDED(hr)) {
// Now you can work with the pElement
BSTR innerText = NULL;
hr = pElement->get_innerText(&innerText);
if (SUCCEEDED(hr)) {
// innerText contains the text of the element
// Handle it as needed
SysFreeString(innerText);
}
pElement->Release();
}
}
else {
// Handle the case where pDisp is null
}
pDisp->Release();
}
}
}
pCollection->Release();
}
doc->close();
SafeArrayDestroy(sa);
}
}
}
int main()
{
CoInitialize(NULL);
IHTMLDocument2* doc = NULL;
HRESULT hr = CoCreateInstance(CLSID_HTMLDocument, NULL, CLSCTX_INPROC_SERVER, IID_IHTMLDocument2, (void**)&doc);
if (SUCCEEDED(hr)) {
LPCWSTR content = L"<html><head><title>Sample HTML</title></head><body><p>Hello, World!</p></body></html>";
LPCWSTR baseURL = L"";
WriteHT(doc, content, baseURL);
// Release the document interface
doc->Release();
}
CoUninitialize();
return 0;
}