Golang calling the Windows DLL method through Syscall

Source: Internet
Author: User
Tags ole

This use case is compiled and executed on GO 1.4.2 , directly on code:

package mainimport  (     "FMT"      "Syscall"       "Time"      "unsafe") const  (    MB_OK                 = 0x00000000     MB_OKCANCEL          = 0x00000001     MB_ABORTRETRYIGNORE  = 0x00000002    MB_YESNOCANCEL        = 0x00000003    MB_YESNO              = 0x00000004    MB_RETRYCANCEL        = 0x00000005    MB_CANCELTRYCONTINUE =  0x00000006    mb_iconhand          =  0x00000010    mb_iconquestion      = 0x00000020     mb_iconexclamation   = 0x00000030    mb_iconasterisk       = 0x00000040    MB_USERICON           = 0x00000080    MB_ICONWARNING        = MB_ICONEXCLAMATION    MB_ICONERROR          = mb_iconhand    mb_iconinformation   = mb_ iconasterisk    mb_iconstop          =  mb_iconhand    mb_defbutton1 = 0x00000000    mb_ defbutton2 = 0x00000100    mb_defbutton3 = 0x00000200     mb_defbutton4 = 0x00000300) Func abort (Funcname string, err syscall. Errno)  {    panic (funcname +  " failed: "  + err. Error ())}var  (    //    kernel32, _         = syscall. LoadLibrary ("kernel32.dll")     //    getmodulehandle, _ =  syscall. GetProcAddress (kernel32,  "Getmodulehandlew")     user32, _      = syscall. LoadLibrary ("User32.dll")     messagebox, _ = syscall. GetProcAddress (user32,  "MessageBoxW")) Func intptr (N int)  uintptr {     return uintptr (n)}func strptr (s string)  uintptr {    return  uintptr (unsafe. Pointer (Syscall. Stringtoutf16ptr (s)))}func messagebox (Caption, text string,&nbsP;STYLE UINTPTR)   (result int)  {    ret, _, callerr :=  syscall. Syscall9 (messagebox,        4,         0,        strptr (text),         strptr (caption),        style,         0, 0, 0, 0, 0)     if callerr ! = 0 {        abort ("Call messagebox",  CALLERR)     }    result = int (ret)     return}// Func getmodulehandle ()   (handle uintptr)  {//    if ret, _,  callerr := syscall. Syscall (getmodulehandle, 0, 0, 0, 0);  callerr != 0 {//        abort ("Call getmodulehandle",  CALLERR)//     } else {//        handle = ret//     }//    return//}// windows Another DLL method called Func showmessage2 (title,  text string)  {    user32 := syscall. Newlazydll ("User32.dll")     messageboxw := user32. Newproc ("MessageBoxW")     messageboxw.call (IntPtr (0),  strptr (text),  strptr (title ),  intptr (0))}func main ()  {    //    defer syscall . FreeLibrary (KERNEL32)     defer syscall. FreeLibrary (USER32)     //fmt. Printf ("retern: %d\n",  messagebox ("Done title",  "This test is done.",  Mb_yesnocancel))     num := messageBox ("Done title",  "This test is done.",  mb_yesnocancel)      Fmt. Printf ("get retrun value before messagebox invoked: %d\n",  num)      showmessage2 ("Another DLL method call under Windows",  "hello !")     time. Sleep (3 * time. Second)}func init ()  {    fmt. Print ("Starting up\n")}


Operating effect:

---

Syscall Extended reading:

Golang OLE Invoke Toolkit

Https://github.com/mattn/go-ole

---

The following are the sources: http://wendal.net/2013/0406.html


Syscall. Syscall Series Method

Currently a total of 5 methods

Syscall. Syscallsyscall.Syscall6syscall.Syscall9syscall.Syscall12syscall.Syscall15

corresponding to 3/6/9/12/15 parameters or the following calls

Parameters are all shaped like

Syscall. Syscall (Trap, Nargs, A1, A2, A3)

The second parameter, Nargs, is the number of arguments, once the error is passed, the call fails, and the heavy person directly Appcarsh

Extra parameters, replace with 0

Invoke Example

Get disk space

First, prepare the input parameters, GetDiskFreeSpaceEx need 4 parameters, can check msdndir: = "C:" lpfreebytesavailable: = Int64 (0)
Note that the type needs to match the type of API lptotalnumberofbytes: = Int64 (0) Lptotalnumberoffreebytes: = Int64 (0)
Gets the reference kernel32 of the method, err: = Syscall. LoadLibrary ("Kernel32.dll")
Strictly speaking, we need to add defer syscall. FreeLibrary (KERNEL32)
GetDiskFreeSpaceEx, err: = Syscall. GetProcAddress (Syscall. Handle (KERNEL32), "GETDISKFREESPACEEXW")
Execute it. Because there are 4 parameters, so take Syscall6 can be put down. The last 2 parameters, the natural is 0 R, _, errno: = Syscall. Syscall6 (UIntPtr (GetDiskFreeSpaceEx), 4,
UIntPtr (unsafe. Pointer (Syscall. Stringtoutf16ptr ("C:")),
UIntPtr (unsafe. Pointer (&lpfreebytesavailable)),
UIntPtr (unsafe. Pointer (&lptotalnumberofbytes)),
UIntPtr (unsafe. Pointer (&lptotalnumberoffreebytes)), 0, 0)
Note that errno is not an error interface and cannot be nil//and, according to the MSDN instructions, the return value is 0 for fail, and not 0 is success if r! = 0 {
Log. Printf ("Free%DMB", lptotalnumberoffreebytes/1024/1024)}
a simple way? with Syscall. Pager

As with the Syscall series, the call method has up to 15 parameters. The method used here to must the beginning, if not present, will panic.

H: = Syscall. Mustloaddll ("kernel32.dll")
c: = H.mustfindproc ("GETDISKFREESPACEEXW")
Lpfreebytesavailable: = Int64 (0)
Lptotalnumberofbytes: = Int64 (0)
Lptotalnumberoffreebytes: = Int64 (0)
R2, _, Err: = C.call (UIntPtr (unsafe). Pointer (Syscall. Stringtoutf16ptr ("F:")),
UIntPtr (unsafe. Pointer (&lpfreebytesavailable)),
UIntPtr (unsafe. Pointer (&lptotalnumberofbytes)),
UIntPtr (unsafe. Pointer (&lptotalnumberoffreebytes)))
If r2! = 0 {
Log. PRINTLN (R2, err, lpfreebytesavailable/1024/1024)

Golang calling the Windows DLL method through Syscall

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.