调用第三方c库函数,接口有个回调函数指针
参考这个网址
https://github.com/golang/go/wiki/cgo#function-pointer-callbacks
例如:
// .h
typedef void(*TestCall)(char ** p);
void TestCallBack(TestCall func);
// .cpp
void TestCallBack(TestCall func)
{
char actemp1[20] = "test TestCallBack";
char* p = actemp1;
char* actemp[1] = { p };
func(actemp);
}
将这段代码编译成动态库
在go调用 TestCallBack
需要做一个桥接
桥接go代码
package main
/*
#include <stdio.h>
void test_go_callback(char ** p);
// The gateway function
void TestCallGDll_brige(char ** p)
{
test_go_callback(p);
}
*/
import "C"
真正的go调用c代码
package main
/*
#cgo CFLAGS: -Icpp
#cgo LDFLAGS: -Llib -ltestdll
#include "testdll.h"
void TestCallGDll_brige(char ** p);
*/
import "C"
import (
"fmt"
"unsafe"
)
//export test_go_callback
func test_go_callback(p **C.char){
var tmp *C.char = *p
str := C.GoString(tmp)
fmt.Println("test_go_callback:", str)
}
func test_dll_callback() {
C.TestCallBack((C.TestCall)(unsafe.Pointer(C.TestCallGDll_brige)))
}