SoFunction
Updated on 2025-03-05

Golang compiles into DLL files

First write the golang program:

package main
import "C"
import "fmt"
 
//export PrintBye
 
func PrintBye() {
    ("From DLL: Bye!")
}
//export Sum
 
func Sum(a int, b int) int {    
return a + b;
}
func main() {    
// Need a main function to make CGO compile package as C shared library
}
   

Compile into DLL file:

go build -buildmode=c-shared -o  

After compilation, we get two files and .

Supplement: Go1.10 is compiling into a small dll instance

Look at the code ~

package main
import (
    "net"
)
// Must importimport "C"
//Compiling into a dynamic library is also a mustfunc main() {}
//export Interfaces
func Interfaces(list []string, retlen *int) string {
    interf, err := ()
    if err != nil {
        return ()
    }
    for i, v := range interf {
        if i >= len(list) {
            break
        }
        list[i] = ()
    }
    *retlen = len(list)
    return ""
}

Compile command:

go build -ldflags "-s -w" -buildmode=c-shared -o  

Two files will be generated in the current folder

Here is the use:

#include <>
#include<>
#include <>
#include ""
int main()
{ 
    GoString ret;
    GoSlice slice;
    =10;
    =0;
    =calloc(10,sizeof(GoString));
    GoInt retlen=0;
    ret=Interfaces(slice,&retlen);
    if ( != 0)
    {
        char* retc = calloc(+1,sizeof(char));
        memcpy(retc,,);
        printf("Return value:%s\n", retc); 
        free(retc);
        retc=NULL;
    }
    GoString* st=(GoString*)();
    for (int i=0;i<retlen;i++)
    {
        printf("%s\n", st[i].p);
    }
    free();
    =NULL;
    return 0;
}

Try not to use the return value to handle it in C, because Go code cannot store pointers to Go allocated memory in C allocated memory. This is very important, otherwise you will crash variously during use.

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.