golang之cgo---调用C/C++动态库函数

前端之家收集整理的这篇文章主要介绍了golang之cgo---调用C/C++动态库函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

  之前说过golang调用C代码的方式可以通过cgo或者是swig,而cgo是不能使用C++相关的东西的,比如标准库或者C++的面向对象特性。怎么办,将c++的功能函数封装成C接口,然后编译成动态库,或者是功能较为简单的可以直接嵌入到go源文件中。
  cgo的使用是在linux平台上,在windows平台上可以配置交叉编译器。

  1. 动态库头文件myfuns.h
  1. #pragma once
  2.  
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include <stdbool.h>
  7.  
  8. void fun1();
  9.  
  10. void fun2(int a);
  11.  
  12. int func3(void **b);
  13.  
  14. // others
  1. 动态库名:myfuns.so

  

  1. 项目简化结构:
  1. |-project
  2. | |-lib
  3. | | |-myfuns.so
  4. | |-include
  5. | | |-myfuns.h
  6. | |-src
  7. | | |-main.go
  8. | |-pkg
  9. | |-bin
  1. go链接动态库:main.go
  1. package main
  2.  
  3. /* #cgo CFLAGS : -I../include #cgo LDFLAGS: -L../lib -lmyfuns #include "myfuns.h" */
  4. import "C"
  5.  
  6. import (
  7. "fmt"
  8. )
  9.  
  10. func main() {
  11. // 调用动态库函数fun1
  12. C.fun1()
  13. // 调用动态库函数fun2
  14. C.fun2(C.int(4))
  15. // 调用动态库函数fun3
  16. var pointer unsafe.Pointer
  17. ret := C.fun3(&pointer)
  18. fmt.Println(int(ret))
  19. }

  通过CFLAGS配置编译选项,通过LDFLAGS链接指定目录下的动态库。这里需要注意的一个地方就是import "C"是紧挨着注释的,没有空行。

猜你在找的Go相关文章