Search code examples
pythonccomui-automation

How to convert BSTR to String with C


I am developing a function in C to extract the class name of UI element. The function returns BSTR and I want to pass this value to python using Py_BuildValue.

BSTR element_class;

hr = IUIAutomationElement_get_CurrentClassName(element,element_class);
if(SUCCEEDED(hr)){
  arglist = Py_BuildValue("(z)", element_class);
}

if(element_class != NULL)
      free(element_class); ????

I am getting the following warning after compiling:

'function': 'BSTR *' differs in levels of indirection from 'BSTR'

I want to understand this warning and how to do it correctly. Also, I would like to free the memory of this element_class and I do not how to do it as well. I appreciate a lot your help.

EDIT 1: I achieved to delete the warning, just adding $ in element_class. However, when I use the Py_BuildValue, I am getting only the first letter and not the whole name of the class.


Solution

  • Putting together all the hints contained in the comments, I think this is what you should be using.

    BSTR element_class;
    
    hr = IUIAutomationElement_get_CurrentClassName(element, &element_class);
    if(SUCCEEDED(hr)){
      arglist = Py_BuildValue("(u)", element_class);
    }
    
    if(element_class != NULL)
          SysFreeString(element_class);