sergioMoreno
sergioMoreno

Reputation: 354

Assign value from VARIANT to BSTR * in plain C

I am using the following code to get the current URL in the browser.

...
BSTR url = NULL;
getUrl(&url);
...

void getUrl(BSTR *url){
...
VARIANT urlValue;
  VariantInit(&urlValue);
...
hr = IUIAutomationElement_GetCurrentPropertyVlue(pUrlBar,UIA_ValueValuePropertyId,&urlValue);
if(SUCCEEDED(hr)){
  url= &urlValue.bstrVal;
  }
}

I am getting null from the variable url. I am wondering if I assigned correctly the value from the VARIANT urlValue. How do I get the value correctly?.

Upvotes: 1

Views: 774

Answers (1)

Joseph Willcoxson
Joseph Willcoxson

Reputation: 6050

Into your function getUrl() you are passing a BSTR*.

void getUrl(BSTR*);

You have to dereference the pointer to properly set the value of the original BSTR:

if (SUCCEED(hr) && urlValue.vt == VT_BSTR) {
   *url = urlValue.bstrVal;
}

Consider where you might have an int pointer:

// bad implementation
void getInt(int* pint) {
   pint = 3; // bad, but basically what you had originally
}

//good
void getInt(int* pint) {
   *pint = 3; // correct, dereferencing allows changing the int that pint points to
}

Some people call that the "call by reference" method for passing arguments in C. https://www.tutorialspoint.com/cprogramming/c_function_call_by_reference.htm or https://www.geeksforgeeks.org/difference-between-call-by-value-and-call-by-reference/

Don't get it confused with C++ which has real call by reference with a different syntax, but under the hood the compiler will treat roughly the same.

Upvotes: 1

Related Questions