Oxygen Basic
Programming => Problems & Solutions => Topic started by: on October 13, 2018, 03:55:59 AM
-
#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.
-
3 solutions:
#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
-
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.
-
wait a moment ...
is that string casting...
function Foo () as string2
return (bstring) SysAllocString("Test string")
end function
-
Yes, it tells the compiler that SysAllocString returns a bstring, not just a number.
-
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.