简介
golang调用c语言动态库,动态方式调用,可指定动态库路径,无需系统目录下
核心技术点
- 封装c动态库
- go语言调用c代码
实例代码
int test_so_func(int a,int b);
#include "test_so.h"
int test_so_func(int a,int b)
{
return a*b;
}
/*
#include "loadso.h"
#cgo LDFLAGS: -ldl
*/
import "C"
import "fmt"
func main() {
fmt.Println("20*30=", C.do_test_so_func(20, 30))
}
- loadso.h
int do_test_so_func(int a,int b);
- loadso.c
#include "loadso.h"
#include <dlfcn.h>
char dllname[]= "/root/test_so.so";
int do_test_so_func(int a,int b)
{
void* handle;
typedef int (*FPTR)(int,int);
handle = dlopen(dllname, 1);
if(handle == 0){
return -1;
}
FPTR fptr = (FPTR)dlsym(handle, "test_so_func");
int result = (*fptr)(a,b);
return result;
}
关联知识
nm -D *.do
# nm -D libhi.so
0000000000201028 B __bss_start
w __cxa_finalize
000000000000063d T Echo
0000000000201028 D _edata
0000000000201030 B _end
0000000000000658 T _fini
w __gmon_start__
000000000000062a T hi
0000000000000500 T _init
w _ITM_deregisterTMCloneTable
w _ITM_registerTMCloneTable
U puts