c语言goout函数,cgo,如何让被嵌入的c语言代码调用golang

满意答案

00e27ab806e4881f8254fe7ae8741834.png

l120816673

2018.06.29

00e27ab806e4881f8254fe7ae8741834.png

采纳率:47%    等级:10

已帮助:520人

/*void callback(void *f);

void callGoFoo(void);

void callGoStackCheck(void);

void callPanic(void);

int callGoReturnVal(void);

int returnAfterGrow(void);

int returnAfterGrowFromGo(void);

void callGoWithString(void);*/import "C"import ( "path"

"runtime"

"strings"

"sync"

"testing"

"unsafe")// Pass a func value from nestedCall to goCallback using an integer token.var callbackMutex sync.Mutexvar callbackToken intvar callbackFuncs = make(map[int]func())// nestedCall calls into C, back into Go, and finally to f.func nestedCall(f func()) { // callback(x) calls goCallback(x)

callbackMutex.Lock()

callbackToken++

i := callbackToken

callbackFuncs[i] = f

callbackMutex.Unlock() // Pass the address of i because the C function was written to // take a pointer. We could pass an int if we felt like // rewriting the C code.

C.callback(unsafe.Pointer(&i))

callbackMutex.Lock()

delete(callbackFuncs, i)

callbackMutex.Unlock()

}//export goCallbackfunc goCallback(p unsafe.Pointer) {

i := *(*int)(p)

callbackMutex.Lock()

f := callbackFuncs[i]

callbackMutex.Unlock() if f == nil {

panic("missing callback function")

}

f()

}

func testCallback(t *testing.T) { var x = false

nestedCall(func() { x = true }) if !x {

t.Fatal("nestedCall did not call func")

}

}

func testCallbackGC(t *testing.T) {

nestedCall(runtime.GC)

}

func testCallbackPanic(t *testing.T) { // Make sure panic during callback unwinds properly.

if lockedOSThread() {

t.Fatal("locked OS thread on entry to TestCallbackPanic")

}

defer func() {

s := recover() if s == nil {

t.Fatal("did not panic")

} if s.(string) != "callback panic" {

t.Fatal("wrong panic:", s)

} if lockedOSThread() {

t.Fatal("locked OS thread on exit from TestCallbackPanic")

}

}()

nestedCall(func() { panic("callback panic") })

panic("nestedCall returned")

}

func testCallbackPanicLoop(t *testing.T) { // Make sure we don't blow out m->g0 stack.

for i := 0; i < 100000; i++ {

testCallbackPanic(t)

}

}

func testCallbackPanicLocked(t *testing.T) {

runtime.LockOSThread()

defer runtime.UnlockOSThread() if !lockedOSThread() {

t.Fatal("runtime.LockOSThread didn't")

}

defer func() {

s := recover() if s == nil {

t.Fatal("did not panic")

} if s.(string) != "callback panic" {

t.Fatal("wrong panic:", s)

} if !lockedOSThread() {

t.Fatal("lost lock on OS thread after panic")

}

}()

nestedCall(func() { panic("callback panic") })

panic("nestedCall returned")

}

00分享举报

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值