qixiaoning
2025-08-22 0f97177f258c67397b206b70e5aea2b24a4868c1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
 
/*
#cgo LDFLAGS: -ldl
#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <errno.h>
 
void* load_so(char* path) {
    void* handle = dlopen(path, RTLD_LAZY);
    if (!handle) {
        fprintf(stderr, "failed to open so:%s, error:%d\n", path, errno);
        return NULL;
    }
 
    printf("succeeded to load so:%s\n", path);
 
    return handle;
}
 
int so_incr(void* handle, int i) {
    typedef int (*p_inc)(int i);
    p_inc f = (p_inc)dlsym(handle, "printlog");
 
    return f(i);
}
 
void release_so(void* handle) {
    dlclose(handle);
}
 
*/
import "C"
import (
    "fmt"
    "io"
    "os"
    "unsafe"
    "embed"
)
 
//go:embed static
var local embed.FS
 
func main() {
    in, err := local.Open("static/libs/libtest.so")
    if nil != err {
        fmt.Println("failed to read file", err)
    } else {
        fmt.Println("load dll okay")
    }
 
    path := "./embed-" + "libtest.so"
    out, err := os.Create(path)
    if nil != err {
        fmt.Println("create backup failed")
    }
 
    _, err = io.Copy(out, in)
    _ = in.Close()
    _ = out.Close()
    if nil == err {
        fmt.Println("copy file failed")
    }
 
    soFile := C.CString(path)
    defer C.free(unsafe.Pointer(soFile))
 
    handle := C.load_so(soFile)
    if nil != handle {
        v := C.so_incr(handle, C.int(5))
        C.release_so(handle)
 
        fmt.Println("return value from so:", int(v))
    }
}