Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to import a DLL function written in C using GO?

Tags:

c

import

go

dll

I'm looking for an example code how import a function from a dll written in C. equivalent to DllImport of C#.NET. It's possible? I'm using windows. any help is appreciated. thanks in advance.

like image 961
The Mask Avatar asked Nov 22 '11 18:11

The Mask


People also ask

How do I use a DLL file?

Once you find the folder, hold the Shift key and right-click the folder to open the command prompt directly in that folder. Type "regsvr32 [DLL name]. dll" and press Enter. This function can add the DLL file to your Windows Registry, helping you access your DLL file.

What is the use of DLL file in C#?

A DLL is a library that contains code and data that can be used by more than one program at the same time. For example, in Windows operating systems, the Comdlg32 DLL performs common dialog box related functions. Each program can use the functionality that is contained in this DLL to implement an Open dialog box.

What is DLL file in C++?

In Windows, a dynamic-link library (DLL) is a kind of executable file that acts as a shared library of functions and resources. Dynamic linking is an operating system capability. It enables an executable to call functions or use resources stored in a separate file.


2 Answers

There are a few ways to do it.

The cgo way allows you to call the function this way:

import ("C")
...
C.SomeDllFunc(...)

It will call libraries basically by "linking" against the library. You can put C code into Go and import the regular C way.

There are more methods such as syscall

import (
    "fmt"
    "syscall"
    "unsafe"
)

// ..

kernel32, _        = syscall.LoadLibrary("kernel32.dll")
getModuleHandle, _ = syscall.GetProcAddress(kernel32, "GetModuleHandleW")

...

func GetModuleHandle() (handle uintptr) {
    var nargs uintptr = 0
    if ret, _, callErr := syscall.Syscall(uintptr(getModuleHandle), nargs, 0, 0, 0); callErr != 0 {
    abort("Call GetModuleHandle", callErr)
    } else {
        handle = ret
    }
    return
}

There is this useful github page which describes the process of using a DLL: https://github.com/golang/go/wiki/WindowsDLLs

There are three basic ways to do it.

like image 78
Another Prog Avatar answered Oct 15 '22 11:10

Another Prog


Use the same method that the Windows port of Go does. See the source code for the Windows implementation of the Go syscall package. Also, take a look at the source code for the experimental Go exp/wingui package

like image 45
peterSO Avatar answered Oct 15 '22 10:10

peterSO