Golang1.7使用CGO在Go代码中定义C函数
发布时间:2020-12-16 18:26:22 所属栏目:大数据 来源:网络整理
导读:test.h文件内容: int test( void * fn); void println( char * str ); void callback( void * fn); test.c文件内容:#include test.h int test(void* fn ) { callback ( fn ); println ( "Hello,This from Clang" ); return 0 ;} main. go 文件代码: package
test.h文件内容:
int test(void* fn);
void println(char* str);
void callback(void* fn);
test.c文件内容:
#include <test.h>
int test(void* fn) { callback(fn); println("Hello,This from Clang");
return 0;
}
main.go文件代码:
package main
import (
"fmt"
"unsafe"
)
/* #cgo CFLAGS: -I./ #include <test.h> */
import "C"
/* CFLAGS 上边指示了头文件地址 LDFLAGS 下边的表明了库文件地址 都是当前文件的相对位置 -I (大写)指示了头文件目录 -L 指示了库文件目录 -l(L小写)指示所用的具体的某个库文件 */
//export println
func println(str *C.char) {
fmt.Println(C.GoString(str))
}
//export callback
func callback(ptr unsafe.Pointer) {
f := *(*func(str *C.char))(ptr)
f(C.CString("Hello,This from Golang"))
}
func main() {
var fn = println
C.test(unsafe.Pointer(&fn))
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |