补充 使用 Go Plugin.

Signed-off-by: chen.yang <chen.yang@yuzhen-iot.com>
This commit is contained in:
chen.yang 2021-12-13 18:49:07 +08:00
parent 61b1d34158
commit c67a359f5d
1 changed files with 68 additions and 4 deletions

View File

@ -1,16 +1,14 @@
# CGO 交叉编译(for ARM32)
通过 Golang 调用 C 共享库,并交叉编译,运行在 arm32bit 平台。
## 1. 安装 C 交叉编译器
```bash
sudo apt install gcc-arm-linux-gnueabihf
```
## 2. 示例代码
## 2. Go 链接 C 共享库
C 语言 demo 共享库如下:
通过 Golang 调用 C 共享库,并交叉编译,运行在 arm32bit 平台。C 语言 demo 共享库如下:
```cpp
/**
@ -65,3 +63,69 @@ func main() {
arm-linux-gnueabihf-gcc -shared -o libdemo.so demo.c
CGO_ENABLED=1 GOOS=linux GOARCH=arm CC=arm-linux-gnueabihf-gcc go build
```
需要将 libdemo.so 和 main 程序一起上传到目标系统。
## 3. 使用 Go Plugin
首先,创建一个提供方法的文件 print.go
```go
package print
import (
"fmt"
)
func PrintTest(strInput string) {
fmt.Println("string in print.so is:", strInput)
}
```
编译 Go Plugin 命令,生成 print.so
```bash
CGO_ENABLED=1 GOOS=linux GOARCH=arm CC=arm-linux-gnueabihf-gcc go build -buildmode=plugin
```
再新建 main 包用于测试:
```go
package main
import (
"fmt"
"plugin"
)
func main() {
// 打开动态库
plug := "./print.so"
pdll, err := plugin.Open(plug)
if err != nil {
fmt.Println("Can not open " + plug)
return
}
// 获取动态库方法
funcPrint, err := pdll.Lookup("PrintTest")
if err != nil {
fmt.Println("Can not Lookup PrintTest")
return
}
// 动态库方法调用
funcPrint.(func(string))("hello go plugin")
}
```
编译 main 包:
```bash
CGO_ENABLED=1 GOOS=linux GOARCH=arm CC=arm-linux-gnueabihf-gc
```
需要将 print.so 和 main 程序一起上传到目标系统。
## 内部参考关键字
1. Go Plugingo 动态库)
2. Build and Use Go Packages as C Libraries