strptr problem with variable

New to FreeBASIC? Post your questions here.
S.ean
Posts: 6
Joined: Feb 20, 2009 8:31

strptr problem with variable

Postby S.ean » Feb 20, 2009 8:45

I am using STRPTR in a dll function that I created to pass a string value back to a program of mine.

All works well when I use a literal value in STRPTR eg STRPTR("HELLO"),
but when I try using a variable i.e

Code: Select all

DIM stVar AS STRING
stVar = "HELLO"
RETURN STRPTR(stVar)  'RETURN STRPTR("HELLO") does work though!!


then it does'nt work. Any ideas of why it is not.

Here is the function

Code: Select all

PUBLIC FUNCTION REPEAT CDECL ALIAS "REPEAT" (numTimes AS INTEGER,stRepeat AS ZSTRING PTR) AS ZSTRING PTR EXPORT
        DIM AS STRING stTemp
        stTemp = *stRepeat
        DIM AS INTEGER counter,repeatLen
        counter = 1
        DO
            stTemp = stTemp & stTemp
            counter *= 2
        LOOP WHILE (counter < numTimes)
        repeatLen = numTimes * LEN(*stRepeat)
        stTemp = LEFT(stTemp,repeatLen)
        RETURN STRPTR(stTemp)
END FUNCTION 


I use this dll in a liberty basic program like this :-

Code: Select all

CALLDLL #lib2,"REPEAT", n AS long, b$ AS PTR, result as long
print winstring(result)


I would really appreciate any help!






jevans4949
Posts: 1148
Joined: May 08, 2006 21:58
Location: Crewe, England

Postby jevans4949 » Feb 20, 2009 9:00

When you exit a function, any variables declared within the function disappear.

A constant would not disappear.

The best thing is either to return a string from the function, in which case it would be passed back to the caller's variable, or else pass the target string as a parameter BYREF and set the target within the function.

If you HAVE to pass back a pointer, then you could declare a STATIC variable in the function, but I wouldn't recommend it.
counting_pine
Site Admin
Posts: 6174
Joined: Jul 05, 2005 17:32
Location: Manchester, Lancs

Postby counting_pine » Feb 20, 2009 9:03

The string, and its data, cease to exist after the function exits. So the pointer you return will no longer be valid.

If you use Static instead of Dim, the string and data will remain in memory between function calls, and the pointer will be safe to use until next time you modify the string.

Can I assume that Liberty Basic doesn't deallocate the pointer it receives? If it does, you will run into trouble next time you try to use the string.
S.ean
Posts: 6
Joined: Feb 20, 2009 8:31

Great - works.

Postby S.ean » Feb 20, 2009 9:54

Thank you both.

Code: Select all

STATIC AS STRING stTemp 'instead of DIM


did the trick.

I have a similar BCX function which worked as expected without the STATIC keyword. I guess the compiler there must have static built in there somehow.

I am very pleased, thanks again.

Return to “Beginners”

Who is online

Users browsing this forum: No registered users and 1 guest