Link to home
Start Free TrialLog in
Avatar of AmyL
AmyL

asked on

Safearrays and IHtmlDocument2 in C

I am using mshtml in a C application. I have an IWebBrowser2 object and an IHtmlDocument2 object, and I want to use the write method instead of navigate2. I used xxd -i to convert the html document to a giant unsigned char (in hex) and saved it in a header file, which is statically linked into the document. Now, I would like to use that giant unsigned char in the document -> write, however it is expecting a safearray.

I would like to know either how to get the unsigned char into the safearray, or another method to achieve the goal of getting an embedded string into the document->write.

Thanks!
Amy
Avatar of jkr
jkr
Flag of Germany image

SAFEARRAYs are actually pretty straightfoward to use. The following is a slightly change example taken from existing production code:

#include <windows.h>
#ifdef _DEBUG
#include <assert.h>
#define CHECK( x) assert( x)
#else
#define CHECK( x) x 
#endif

SAFEARRAY* CreateSafeArrayFromUCHARPtr(const unsigned char* puc, const size_t sz) {
    SAFEARRAYBOUND	 saBound[ 1];
    HRESULT			 hres;

    saBound->lLbound		=	0;
    saBound->cElements	=	sz;

    CHECK	(	psa	=	SafeArrayCreate	(	VT_UI1,
                                            1,
                                            saBound
                                        )
            );

    for	(	long	lIndex	=	0;	lIndex	<	sz;	lIndex++)
        {
            hres	=	SafeArrayPutElement	(	 psa,
                                                &lIndex,
                                                 puc + lIndex
                                            );

            CHECK	(	S_OK	==	hres);
        }

    return psa;
}

Open in new window


For cleanup, just call 'SafeArrayDestroy()' (http://msdn.microsoft.com/en-us/library/ms891251.aspx)
Avatar of AmyL
AmyL

ASKER

Thank you! That worked for me, except that I realized when looking at the documentation that it has to be a SafeArray of BSTR. (I am referring to the documentation for IHtmlDocument2->write). I'm trying to see if I can convert it now.
Avatar of AmyL

ASKER

Okay, it will work if I do something like:
OLESTR("<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'"), because it looks like it just converts it to L"<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'". My string that I want to use, though, is an unsigned char variable full of hex characters (xxd -i). It doesn't like OLESTR(MyData) because it just literally prepends an "L" to MyData and creates a new variable (LMyData) that has no definition.

Any ideas?

Thanks!
Amy
For BSTRs, that should just be

#include <windows.h>
#ifdef _DEBUG
#include <assert.h>
#define CHECK( x) assert( x)
#else
#define CHECK( x) x 
#endif

SAFEARRAY* CreateSafeArrayFromUCHARPtrArray(const unsigned char** ppuc, const size_t sz) {
    SAFEARRAYBOUND	 saBound[ 1];
    HRESULT			 hres;

    saBound->lLbound		=	0;
    saBound->cElements	=	sz;

    CHECK	(	psa	=	SafeArrayCreate	(	VT_BSTR,
                                            1,
                                            saBound
                                        )
            );

    for	(	long	lIndex	=	0;	lIndex	<	sz;	lIndex++)
        {
            hres	=	SafeArrayPutElement	(	 psa,
                                                &lIndex,
                                                 *(ppuc + lIndex) // or ppuc[lIndex]
                                            );

            CHECK	(	S_OK	==	hres);
        }

    return psa;
}
                                            

Open in new window

>>Any ideas?

Since the docs for 'write()' (http://msdn.microsoft.com/en-us/library/ie/ms536782%28v=vs.85%29.aspx) say "A array of String that specifies the text and HTML tags to write", like th eabove - just provide each tag seperately.
Avatar of AmyL

ASKER

Great, I'll try this tonight. Thanks!!!!
Avatar of AmyL

ASKER

I'm getting a memory access violation here:
hres =      SafeArrayPutElement      (psa,&lIndex,*(ppuc + lIndex));

I'm not sure if I'm setting the ** correctly:
const unsigned char * cptr;
const unsigned char ** cptrtoptr;
cptr = dhtm;  //dhtm is the unsigned char array of hex
cptrtoptr = &cptr;
Avatar of AmyL

ASKER

Okay - I got something that almost works. The only thing wrong is when I cast the unsigned char array to LPCTSTR, I get some odd looking characters. I have the project set to use Unicode. (When I changed it to wide char, I created problems in other parts of the code). Anyways, here is what is almost working:

LPCTSTR htf = (LPCTSTR)(const char *)dhtm;

if ((sfArray = SafeArrayCreate(VT_VARIANT, 1, (SAFEARRAYBOUND *)&ArrayBound)))
{

      if (!SafeArrayAccessData(sfArray, (void**)&pVar))
                  {
                        if (sfArray != NULL) {
                              for (l = 0; l < 1; l++) {
                                    VARIANT vOut;
                                    VariantInit(&vOut);
                                    vOut.vt= VT_BSTR;  // set type
                                    vOut.bstrVal = SysAllocString(htf);
                                    aLong[0]= l;  
                                    if (hr= SafeArrayPutElement(sfArray, aLong, &vOut)) {
                                          VariantClear(&vOut);
                                    SafeArrayDestroy(pSA);
                                    
                                    }
                                    else
                                    {
                                    VariantClear(&vOut);
                                    }
                                    }

                              }
                        }
                  }
>>I have the project set to use Unicode

Then you will have to convert the strings to UNICODE before adding them to the VARIANT, e.g.

    for	(	long	lIndex	=	0;	lIndex	<	sz;	lIndex++)
        {
            size_t len = strlen(*(ppuc + lIndex)) + 1;
            wchar_t* pwsz = (wchar_t*) malloc(len);
            mbstowcs(pwsz,*(ppuc + lIndex),len);
            hres	=	SafeArrayPutElement	(	 psa,
                                                &lIndex,
                                                 pwsz
                                            );

            free(pwsz);

            CHECK	(	S_OK	==	hres);
        }

Open in new window

Avatar of AmyL

ASKER

Thank you so much for all of your help. I am so close.

Now, I can get it correctly with a small-ish char array, but when I put in my "real" one (size is 3895966), it crashes. Can you please check the values in my function call? (The variable dhtm2 is the small one, which seems to work, if I use dhtm instead, it crashes). When I use dhtm2 (the small one), I set the size values smaller also.

unsigned char dhtm2[] = { 0x3c, 0x21, 0x44, 0x4f, 0x43, 0x54, 0x59, 0x50, 0x45, 0x20, 0x68, 0x74, 0 };
const char *orig = (const char *)dhtm2;
    // Convert to a wchar_t*
    size_t convertedChars = 0;
    wchar_t wcstring[3895966];
    mbstowcs_s(&convertedChars, wcstring, 3895966, orig, _TRUNCATE);
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of AmyL

ASKER

Great idea! I'll try that.
size_t len = strlen(*(ppuc + lIndex)) + 1;
wchar_t* pwsz = (wchar_t*) malloc(len);
mbstowcs(pwsz,*(ppuc + lIndex),len);

Open in new window


the code doesn't calculate correct sizes. a wide string needs twice the size of a char array.

you should make the code safer and more robust like ...

if (lIndex < sz) // sz is assumed to be the number of strings
{
      char * p = (char*)ppuc[lIndex];
      if (p != NULL)
      {
           size_t len = strlen(p);
           // when passing NULL for output the required size was returned
          size_t siz = 0;
          if (len > 0)
          {
               siz = mbstowcs(NULL, p, len); 
          }
          // we need 2 bytes more for wchar_t zero termination
          wchar_t * pwsz = (wchar_t*) malloc(siz+sizeof(wchar_t));
           siz = mbstowcs(pwsz, p, len);
           if (siz == (size_t)(-1))
           { 
                // error

Open in new window


Sara
Avatar of AmyL

ASKER

Here was the final verdict (for anyone else trying to achieve this):
Chunking the wstring and sending multiple write() commands did work in that the document loaded into the browser, however it had many caveats, one being that document events (such as "complete") never fired, and the compatibility was never correctly rendered as IE 10+. So, what I ended up doing, was using IPersistStreamInit and sending the whole char array as a stream. That seems to work as expected, events and all.
Thanks!
Amy