Author Topic: BSTR problem  (Read 1783 times)

0 Members and 1 Guest are viewing this topic.

  • Guest
BSTR problem
« on: October 13, 2018, 03:55:59 AM »
Code: [Select]
#unique on
uses oleaut

function Foo () as string2
   dim b as bstr = SysAllocString("Test string")
   return b
end function

dim s as string2 = Foo
print s

print s prints the numeric value of the returned bstr pointer, not the content of the string. Shouldn't the bstr pointer be attached to the returned string?

I'm using this Foo function to demonstrate the problem. In normal O2 code I will return a string2, but there re many COM methods that return a bstr and declaring the return type as string2 doesn't solve it.
« Last Edit: October 13, 2018, 04:27:07 AM by José Roca »

Charles Pegge

  • Guest
Re: BSTR problem
« Reply #1 on: October 13, 2018, 05:21:54 AM »
3 solutions:

Code: [Select]
#unique on
uses oleaut

function Foo1 () as string2
   dim b as bstr
   (sys) b = SysAllocString("Test string")
   function=b
   SysFreeString b
end function

function Foo2 () as string2
   function = (bstring) SysAllocString("Test string")
end function

function Foo () as string2
   return (bstring) SysAllocString("Test string")
end function

dim as string2  s = Foo
print s
« Last Edit: October 13, 2018, 08:41:24 AM by Charles Pegge »

Charles Pegge

  • Guest
Re: BSTR problem
« Reply #2 on: October 13, 2018, 06:51:25 AM »
The conversion to string2 from bstring is automatic.

Because the bstring is returned from a function and transformed into a native o2 string, the garbage collector will grab it for timely disposal.

But this is not the case when passing the value to a bstring variable, which must be disposed of explicitly.

Aurel

  • Guest
Re: BSTR problem
« Reply #3 on: October 13, 2018, 11:58:16 AM »
wait a moment ...
is that string casting...

function Foo () as string2
   return (bstring) SysAllocString("Test string")
end function

Charles Pegge

  • Guest
Re: BSTR problem
« Reply #4 on: October 13, 2018, 03:08:47 PM »
Yes, it tells the compiler that SysAllocString returns a bstring, not just a number.
« Last Edit: October 13, 2018, 06:52:25 PM by Charles Pegge »

  • Guest
Re: BSTR problem
« Reply #5 on: October 13, 2018, 06:37:22 PM »
Thanks, Charles. I try to collect your exaplanations in my draft documentation pages:
https://github.com/JoseRoca/WinPBX/blob/master/docs/Oxygen/Operators.md#explicitcast

In Spain we a have a proverb: "Más vale lápiz corto que memoria larga" (literal translation: "A short pencil is better than a long memory"), meaning that it's better that when you come up with something you write it down, because, otherwise, you can have a hard time remembering it.