This is a creation in Article, where the information may have evolved or changed.
Invocation mode
Func WindowVersion1 () {h, err: = Syscall. LoadLibrary ("kernel32.dll") if err! = Nil {fmt. Printf ("Error:%s\n", err) Return}defer Syscall. FreeLibrary (h) proc, err: = Syscall. GetProcAddress (H, "getversion") if err! = Nil {fmt. Printf ("Error:%s\n", err) Return}r, _, _: = Syscall. Syscall (UIntPtr (proc), 0, 0, 0, 0) Major: = Byte (r) Minor: = Uint8 (R >> 8) Build: = UInt16 (R >>) print ("Windows Version ", Major,". ", Minor," (build ", build,") \ n ")}func WindowVersion2 () {dll32: = Syscall. Newlazydll ("Kernel32.dll") G: = Dll32. Newproc ("GetVersion") R, _, _: = G.call () Major: = Byte (r) Minor: = Uint8 (R >> 8) Build: = UInt16 (R >>) print ("W indows Version ", Major,". ", Minor," (build ", build,") \ n ")}
Invoking C + + DLLs
When used, the exe generated by go and C + + generated DLLs are placed in the same directory.
C++:
vs 2010,c++ Embedding ":: MessageBox (NULL, str, _t (" ... "), MB_OK);" This will cause the program to crash when used for debugging.
Dlltest.hdll_api int __stdcall test1 (LPTSTR s);D Ll_api int __stdcall test2 (int *m);//dlltest.cppint __stdcall Test1 ( LPTSTR s) {CStringA sz (s); Cout<<sz<<endl;return 0;} int __stdcall test2 (int *m) {*m=*m*3+1;return 123;}
Go
Func callDll1 () {dll32: = Syscall. Newlazydll ("Dlltest.dll") fmt. Println ("DLL name:", Dll32. Name) G: = Dll32. Newproc ("_test1@4") s: = "1k China fd" R1, _, _: = G.call (UIntPtr (unsafe. Pointer (Syscall. Stringtoutf16ptr (s))) Fmt. Println ("callDll1 result:", R1)}func callDll2 () {dll32: = Syscall. Newlazydll ("Dlltest.dll") G: = Dll32. Newproc ("_test2@4") var m int32m = 10p: = &mfmt. Printf ("% #v \ n", p) R1, _, _: = G.call (UIntPtr (unsafe). Pointer (P))) FMT. Println ("CallDll2 Result:", (Int32) (R1))//Gets the modified m-value FMT. Println (* (*int32) (unsafe. Pointer (P)))//Return 31}
DLL tries to return *string error reason: Golang string is the struct at the end of Len, the C + + string is the end of ' ""., the underlying data results are different. So when you use a DLL to pass in outgoing data, Be careful about the consistency of the underlying data types.