Golang1.7使用CGO在Go代码中定义C函数

前端之家收集整理的这篇文章主要介绍了Golang1.7使用CGO在Go代码中定义C函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. test.h文件内容:
  2. int test(void* fn);
  3. void println(char* str);
  4. void callback(void* fn);
  1. test.c文件内容:
  2. #include <test.h>
  3. int test(void* fn) { callback(fn); println("Hello,This from Clang");
  4. return 0;
  5. }
  1. main.go文件代码:
  2. package main
  3.  
  4. import (
  5. "fmt"
  6. "unsafe"
  7. )
  8.  
  9. /* #cgo CFLAGS: -I./ #include <test.h> */
  10. import "C"
  11.  
  12. /* CFLAGS 上边指示了头文件地址 LDFLAGS 下边的表明了库文件地址 都是当前文件的相对位置 -I (大写)指示了头文件目录 -L 指示了库文件目录 -l(L小写)指示所用的具体的某个库文件 */
  13.  
  14. //export println
  15. func println(str *C.char) {
  16. fmt.Println(C.GoString(str))
  17. }
  18.  
  19. //export callback
  20. func callback(ptr unsafe.Pointer) {
  21. f := *(*func(str *C.char))(ptr)
  22. f(C.CString("Hello,This from Golang"))
  23. }
  24.  
  25. func main() {
  26. var fn = println
  27. C.test(unsafe.Pointer(&fn))
  28. }

猜你在找的Go相关文章