Anyone have GetEnvironmentVariable working?

BlitzMax Forums/BlitzMax Programming/Anyone have GetEnvironmentVariable working?

Gabriel(Posted 2006) [#1]
I'm probably misreading the MSDN docs on this ( not for the first time ) but this doesn't work :

Extern "Win32"
   Function GetEnvironmentVar:Int(Variable$z,Value$z,Length:Int) = "GetEnvironmentVariableA@12"	
End Extern


Function GetEnvironmentVariable:String(EnvVarName:String)
   Local Ret:String
   Local L:Int=32767
   If GetEnvironmentVar(EnvVarName,Ret,L)=0
      Return ""
   Else
      Return Ret
   End If
End Function


More specifically, it crashes and the debugger shuts itself down, so there's no possible way to see what it did or where it got to. I'm pretty sure it exits the function after being called, but since it shuts down, something obviously went wrong. And it doesn't get the correct value anyway.

EDIT: Correction, it does NOT exit the function. The debugger just writes something to the debuglog for no apparent reason before it crashes. Go figure.


Eikon(Posted 2006) [#2]
Here's the code I use (hat tip to Indie)

Function GetEnvironmentVariableA(VarName:Byte Ptr,back:Byte Ptr,size:Short)

Function GetEnvVar:String(VarName:String)
		Local TempBank:TBank = CreateBank(1)
		Local size:Int = GetEnvironmentVariableA(Varname,BankBuf(TempBank),1)
		If size > 0
			ResizeBank(Tempbank,Size+1)
			GetEnvironmentVariableA(Varname,BankBuf(TempBank),Size+1)
		Else
			Return ""
		EndIf
		
		Local tString:String = ""
		Local t:Int
		For t = 0 To BankSize(tempbank)-3
			tString = tString + Chr(PeekByte(tempbank,t))
		Next
		
		ResizeBank(TempBank,0)
		FlushMem()
		Return tString
End Function



Gabriel(Posted 2006) [#3]
Ah yeah, I was just gonna go back and see if I could do it with a Bank. Thanks, Eikon.


skidracer(Posted 2006) [#4]
here's the code i use:
Print getenv_("path")

putenv_ "myvar=snot"

Print getenv_("myvar")



Gabriel(Posted 2006) [#5]
Are they using getenv from the standard C lib, Skid? Because Software Passport recommends not using that, as

it does not always recognize changes made to the environment after the program is started



skidracer(Posted 2006) [#6]
Yes I think so.

Interesting, from my experience that would be "never" instead of "not always".


TartanTangerine (was Indiepath)(Posted 2006) [#7]
@Gabriel, The code that Eikon has posted is the stuff I've been using with software passport pro since GEOM.


Yan(Posted 2006) [#8]
Strict

Extern "Win32"
   Function GetEnvironmentVariable(lpName$z, lpBuffer:Byte Ptr, nSize) = "GetEnvironmentVariableA@12" 
End Extern

Print GetEnv("HOMEPATH")

End


Function GetEnv$(envVar$)
  Local buff:Byte[256]
  
  Local rtnLen = GetEnvironmentVariable(envVar$, buff, buff.length) 
  If rtnLen > (buff.length - 1)
    buff = buff[..rtnLen]
    rtnLen = GetEnvironmentVariable(envVar$, buff, buff.length)
  EndIf
  
  Return String.FromBytes(buff, rtnLen)
End Function