Golang调用动态库so

时间:2022-05-06
本文章向大家介绍Golang调用动态库so,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
测试动态库

test_so.h

  1. int test_so_func(int a,int b);

test_so.c

#include "test_so.h"

int test_so_func(int a,int b)

{

    return a*b;

}

生成so

  1. gcc -shared ./test_so.c -o test_so.so

复制so文件到golang项目目录

golang项目目录,建立

load_so.h

  1. int do_test_so_func(int a,int b);

load_so.c

#include "load_so.h"

#include <dlfcn.h>



int do_test_so_func(int a,int b)

{

    void* handle;

    typedef int (*FPTR)(int,int);



    handle = dlopen("./test_so.so", 1);

    FPTR fptr = (FPTR)dlsym(handle, "test_so_func");



    int result = (*fptr)(a,b);

    return result;

}
复制代码
test.go
package main



/*

#include "load_so.h"

#cgo LDFLAGS: -ldl

*/

import "C"

import "fmt"



func main() {

    fmt.Println("20*30=", C.do_test_so_func(20, 30))

    fmt.Println("hello world")

}