This is a creation in Article, where the information may have evolved or changed.
Previously said Golang call C code can be through CGO or swig, and CGO is a 不能使用
C + + related things, such as the standard library or C + + object-oriented features. What to do, the C + + function function is encapsulated into the interface, and then compiled into a dynamic library, or the function is relatively simple can be embedded directly into the go source file.
CGO is used on Linux platforms where cross compilers can be configured on the Windows platform.
动态库头文件:myfuns.h
#pragma once#include <stdio.h>#include <string.h>#include <stdlib.h>#include <stdbool.h>void fun1();void fun2(int a);int func3(void **b);// others
动态库名:myfuns.so
项目简化结构:
|-project| |-lib| | |-myfuns.so| |-include| | |-myfuns.h| |-src| | |-main.go| |-pkg| |-bin
go链接动态库:main.go
package main/*#cgo CFLAGS : -I../include#cgo LDFLAGS: -L../lib -lmyfuns#include "myfuns.h"*/import"C"import ( "fmt")func main() { // 调用动态库函数fun1 C.fun1() // 调用动态库函数fun2 C.fun2(C.int(4)) // 调用动态库函数fun3 var pointer unsafe.Pointer ret := C.fun3(&pointer) fmt.Println(int(ret))}
By CFLAGS
Configuring the Compile option, you LDFLAGS
can link a dynamic library under a specified directory. One thing to note here is that import "C"
there is no blank line next to the comment.