Writing to a var from a julia func that is called externally

Hi. New to Julia, using the Windows 7 32bit API. The “EnumWindows” API func takes the address of a callback procedure (designated “EnumWindowsProc”) and an arbritrary user defined Int as args. It then iterates through the top level windows and calls EnumWindowsProc with a handle to each window and the user Int. EnumWindowsProc should return non-zero to continue.

The following code is to find a given named window - here “Program Manager” for testing purposes.

const U32="USER32"
const windowname="Program Manager"

function getWindowText(hWnd::Int32)
    #wrapper for GetWindowTextA - working, no issues
    return unsafe_string(pointer(buf))

function EnumWindowsProc(hWnd::Cint,param::Cint)
    if getWindowText(hWnd)==windowname 
        println("found window: ",hMyWindow)
        return 0
    return 1

println("EnumWindows returned: ",ccall((:EnumWindows,"USER32"),Cint,(Ptr{Void},Cint),lpEnumFunc,0))
println("handle is: ",hMyWindow)

The EnumWindows call works correctly. When the named window is located in EnumWindowsProc its value is reported by the println("found window: ",hMyWindow) inside that function, however when the EnumWindows call returns hMyWindow is still set to 0

Am I not defining the scope of hMyWindow to include EnumWindowProc so a local hMyWindow is being created? or perhaps is the value being garbage collected on return from EnumWindows?

EnumWindowProc is only called as a callback by the OS and not directly from any Julia code. Another solution could be to use the user param to supply the address of a variable and write it directly there, but this seems a bit overcomplicated. I feel sure there is something simple I am missing here.

Output is:

found window: 65758
EnumWindows returned: 0
handle is: 0

EnumWindows returning 0 is correct as it is being terminated by EnumWindowProc returning 0 when the window is located.

How do I get this handle out of the callback proc back to my julia program?

Here you go :slight_smile:

help?> global
search: global GlobalRef cglobal

  global x makes x in the current scope and its inner scopes refer to the global variable of that name. In the example
  below, global is needed so the function can modify the global variable z:

  function foo()
      global z=6

  julia> foo()
  julia> z

  Without the global declaration in foo(), a new local variable would have been created inside foo(), and the z in the
  global scope would have remained equal to 3.
1 Like

That’s it :slight_smile: thanks @anon67531922. I think I actually tried global in the initial def at one stage, but not when setting the value inside the func. Well spotted.

1 Like