c如何把函数传递到go语言里面去?

go可以接收到这个函数,然后回调

阅读 2.6k
1 个回答
//testgo.h
#ifdef __cplusplus
extern "C"{
#endif
extern long getaddr();
extern int calladdr(long addr);
#ifdef __cplusplus
}
#endif
//testgo.cpp
#include <stdio.h>
#include "testgo.h"

typedef int(*pfun)();

int testfunc(){
    return 123654;
}

long getaddr() {
    return (long)testfunc;
}

int calladdr(long addr){
    return ((pfun)addr)();
}
//test.go
package main

// #include "testgo.h"
// #cgo LDFLAGS: ${SRCDIR}/testgo.so -lstdc++
import "C"
import "fmt"

func main() {
    addr := C.getaddr()
    fmt.Println("addr is", addr)
    fmt.Println("call ret:", C.calladdr(addr))
}

g++ -shared -fPIC testgo.cpp -o testgo.so
go run test.go

通过getaddr取得testfunc的函数地址,再通过calladdr调用地址对应的函数,你看看是不是你想要的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题