win32com, BSTR, and null terminated strings

Matt Helm eric at qwhd746oihd49.net
Sun Feb 5 16:22:52 EST 2006



I am using win32com to access a third party COM interface but am
having trouble using the string that is returned.

The vendor's docs show the following method:
 
    HRESULT CookString(BSTR param_a, short buf_size, [out, retval] BSTR* result_b);

param_a is a string to be processed.
buf_size is the size of the returned string + 1.

I can't know what the exact length of the returned string will be but
it is safe to assume it will not exceed 80 chars.
 
I have been calling it as such:

    import win32com.client

    o = win32com.client.Dispatch("BFG9000.BFG9000")

    r = o.Cook("ABCDEFG", 81)


r comes back as a Python string 81 chars in length with a null at the
end of the actual valid text. In other words, it is your normal buffer
containing a null terminated string.

Python treats the whole 81 chars as valid - even though most of the
string is garbage. This is the expected behavior and I understand
this.

However, what is the proper way to recover the actual string? I have
been using:

    r.split("\0", 1)[0]

but it seems like a bit of a kludge.


Regards,
Matt




More information about the Python-list mailing list