win32com, BSTR, and null terminated strings
Steve Holden
steve at holdenweb.com
Sun Feb 5 23:33:39 EST 2006
Matt Helm wrote:
>
> 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.
>
It's perfectly good Python, though, so just forget about it or wrap it
in a "cstring(s)" function do you don't have to look at it!
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/
More information about the Python-list
mailing list