golang吧 关注:6,549贴子:14,775
  • 6回复贴,共1

go怎么在linux下调用动态库?

只看楼主收藏回复

syscall里的loadlibrary好像只能给windows用……linux下想调用.so应该怎么办?
求大神教育


IP属地:北京1楼2014-10-14 09:25回复
    你可以用c写调用动态库的代码,然后go可以直接嵌入C的代码,也就是cgo
    具体怎么写百度一下
    — —


    IP属地:湖北2楼2014-10-14 11:06
    收起回复
      2026-01-28 08:33:11
      广告
      不感兴趣
      开通SVIP免广告
      http://my.oschina.net/ellice/blog/118644


      IP属地:湖北3楼2014-10-14 11:07
      回复
        package main
        /*#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);
        dlclose(handle);
        return result;
        }
        #cgo LDFLAGS: -ldl
        */
        import "C"
        import "fmt"
        func main() {
        fmt.Println("20*30=", do_test_so_func(20, 30))
        }
        func do_test_so_func(a int, b int) int {
        return int(C.do_test_so_func(C.int(a), C.int(b)))
        }
        我暂时想到的就这样了
        在C里面直接把动态库里的函数调出来,然后在Go里面包装函数。。
        除非你自己包装dlopen和dlsym,但是C里面的函数指针在Go里面不知道要怎么办— —。。


        IP属地:湖北4楼2014-10-15 09:21
        回复