C调用go静态库

2019-03-29  本文已影响0人  ebayboy

Go 生成C动态库.so和静态库.a

源代码

package main

import "C"

import "fmt"

//export hello

func hello(){

    fmt.Println("hello world")

}

//export add

func add(a,b int) int {

    return a+b

}

func main(){

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

注意:生成C可调用的so时,Go源代码需要以下几个注意。

必须导入 “C” 包

必须在可外部调用的函数前加上 【//export 函数名】的注释

必须是main包,切含有main函数,main函数可以什么都不干

编译

先要安装go的标准库

go install -buildmode=shared -linkshared std

1

编译共享库

go build -buildmode=c-shared -o so库文件名 自己的项目

1

然后当前目录就会出现 xxx.h和xxx.so文件

C

#include<stdio.h>

#include"libtest.h" //生成的头文件

void main(){

hello();

printf("\n2+3=%d\n",add(2,3));

}

1

2

3

4

5

6

7

8

编译:

gcc goso.c  -L ./ -ltest -o goso

1

执行

由于是共享库,那么运行时就需要加载需要的库。在linux中默认库的路径为/usr/lib 或者/usr/lib64 。如果想将自己所在的文件夹也添加到库搜索目录中去。那么有两种方式:

修改配置文件,将自己的目录添加到库搜索目录列表中去。/etc/ld.so.conf 然后执行ldconfig

修改环境变量,临时改变库搜索路径。 export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:自己的目录

如何生成静态库

只需要将buildmode改为c-archive即可。然后编译时将静态库参与编译即可。

Go调用C库

源代码

注意:

需要使用到cgo工具

直接在import “C”之前添加一个注释。 然后使用C语法添加库的头文件。

针对共享库由于是操作系统管理程序运行加载的共享库,所以可以不用管,只需要将so库放入对应的目录即可。针对静态库,那么就要在代码中多添加一行,告诉编译器编译时需要连接的库。// #cgo LDFLAGS: -L ./ -lfoo

package main

//#cgo LDFLAGS: -L ./ -lfoo    使用静态库时需要添加

//#include"xxx.h"

import "C"

xxxx

func main(){

    C.xxx(xxx)

}

---------------------

作者:zouxinjiang

来源:CSDN

原文:https://blog.csdn.net/github_33719169/article/details/84827094

版权声明:本文为博主原创文章,转载请附上博文链接!

上一篇下一篇

猜你喜欢

热点阅读