golang調用c動態庫


golang調用c動態庫

簡介

golang調用c語言動態庫,動態方式調用,可指定動態庫路徑,無需系統目錄下

核心技術點

  • 封裝c動態庫
  • go語言調用c代碼

實例代碼

  • 封裝c動態庫
    • 頭文件 test_so.h
    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;
    }
    
  • go語言調用
/*
#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;
}

關聯知識

  • 查看so動態庫的導出函數 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

引文


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM