CGO中处理C中的回调函数

C语言的接口

api.h



#ifndef API_H
#define API_H

#ifdef __cplusplus
extern "C" {
#endif

typedef void (*IntCallback)(void *, int);

void SetIntCallback(IntCallback cb, void *data);

void DoIntCallback(int value);

#ifdef __cplusplus
}
#endif
#endif
  1. 先在CGO中声明一下回调函数需要用到的C函数
package main

/*
#include "api.h"
extern void cgoCall(void *, int); // 这里与api.h中的IntCallback保持类型一致
*/
import "C"
  1. 在Golang中通过 //export方式实现上述的C函数
//此处省略上述重复代码

//export cgoCall
func cgoCall(p unsafe.Pointer, number C.int) {
	// TODO: 这里先留空,我们还没确定传进来的 p是什么具体类型
}
  1. 在Golang中定义一个interface来接收上面的函数里的C.int类型的参数
type Caller interface {
	Call(int)
}
  1. 在完善一下步骤2中的cgoCall
//export cgoCall
func cgoCall(p unsafe.Pointer, number C.int) {
	caller := *(*Caller)(p)
	caller.Call(int(number))
}

说明:
我们在这里将p参数转化为 一个 Caller的interface类型,再调用 Caller类型的Call(int)函数。表明我们在调用 C语言中的SetIntCallback时, data参数给的是一个 Caller类型的指针

  1. 定义一个具体的类型实现 Caller接口测试一下
//此处省略上述重复代码

type OneCaller struct {}
type AnotherCaller struct {}

func (o OneCaller) Call(value int) {
	println("one:", value)
}

func (o AnotherCaller) Call(value int) {
	println("another:", value)
}

func SetCallback(caller Caller) {
	C.SetIntCallback(C.IntCallback(C.cgoCall), unsafe.Pointer(&caller))
}

func DoCallback(value int) {
	C.DoIntCallback(C.int(value))
} 

func main() {
	one := OneCaller {}

	SetCallback(one)	
	DoCallback(1234)
	another := AnotherCaller {}
	
	SetCallback(another)	
	DoCallback(5678)
}

总结
为了使用C语言中的回调函数, 我们使用到了以下技术来实现
unsafe.Pointer:将Go中的指针传入到C语言中的 void *
//export XXX: 在GO 中实现 C语言中声明的函数
通过interface技术将 C语言中的回调函数类型绑定实现了多态或泛型

引用

posted @ 2023-05-15 13:27  jiftle  阅读(375)  评论(0编辑  收藏  举报