Author Topic: Win32 /nasm : Is GetModuleHandle necessary?  (Read 1040 times)

Offline afk

  • Jr. Member
  • *
  • Posts: 11
Win32 /nasm : Is GetModuleHandle necessary?
« on: April 12, 2017, 09:07:34 PM »
Hi all,
Every example I can find of win32 coded in .asm invokes GetModuleHandle which returns the handle to the file used to create the calling process. This value is passed to WinMain as hInstance before WinMain is invoked.

Yet C/C++ examples never call GetModuleHandle. Instead they call WinMain immediately and read  hInstance directly into the struc or API. Apparently, the system installs a value into hInstance at startup.

Calling WinMain in NASM in the style of C/C++ without first calling GetModuleHandle seems to work o.k. Is this for real ? Can I safely omit calling GetModuleHandle ?

Thanks in advance.
afk


Offline Frank Kotler

  • NASM Developer
  • Hero Member
  • *****
  • Posts: 2356
  • Country: us
Re: Win32 /nasm : Is GetModuleHandle necessary?
« Reply #1 on: April 16, 2017, 08:54:47 AM »
I don't know much about Windows. What's MS say about GetModuleHandle? My wild-asmed guess would be that C calls it in the "startup code" - the code that calls "_main" - "behind your back". If your code appears to work without calling GetmoduleHandle... well, if it works it works... Not necessarily "right"... I dunno.

Best,
Frank

P.S. This any help?
http://stackoverflow.com/questions/21718027/getmodulehandlenull-vs-hinstance

« Last Edit: April 16, 2017, 09:02:33 AM by Frank Kotler »

Offline afk

  • Jr. Member
  • *
  • Posts: 11
Re: Win32 /nasm : Is GetModuleHandle necessary?
« Reply #2 on: April 16, 2017, 03:20:47 PM »
Hi Frank,
Thanks for the reply.

As far as the C startup code calling GetModuleHandle my guess was the same as yours except that the values returned are radically different. GetModuleHandle always reports the start of the application code in memory -on my machine with Olly debug it's always around 0040 0000h.

But if I call WinMain without GetModuleHandle then hInstance reports a *very* high hex value on the order of 0ffdf1234.
Yet both values satisfy the system as hInstance.

And if I want to use WinMain directly I find that have to drop into the WinMain proc by "default"

        start:
        proc WinMain (hInstance),. . .etc.
        . . .
        message pump
        . . .
        mov eax, dword [msg +MSG.wParam]
        ret
        endproc

Ending the application directly out of the procedure seems awkward to me but if I trace it in the debugger it does return to the system code for ExitUserThread with no apparent "leftovers".

;----------------------------
It was an interesting experiment but I think that eliminating two lines of code for GetModuleHandle isn't worth the nagging worry that it's there for a reason.

Instead of wasting any more of anyone's time I think I'll stick to the "way we've always
done things around here " ;-)

Thanks again Frank.
afk