问题描述
- 如何从线程用C一个呼叫转到code,它不是由围棋产生的?
- 我怎么分配给一个C函数指针,这样不会被转到创建的线程可以调用该指针,进入围棋code?
- 我不希望使用痛饮。
- 的回调将线程进入以前没有见过到来。无论是
CGO /生活
,也没有任何东西包装/运行
演示此行为AFAICT。
Update0
- I don't want to use SWIG.
- The callbacks will be coming from threads Go hasn't seen before. Neither
cgo/life
nor anything inpkg/runtime
demonstrates this behaviour AFAICT.
推荐答案
您可以这样做,但解决方案是相对较慢(大约每次通话22μs我的机器上)。
答案是为C code用C线与原语将实际运行回调的另一个够程进行通信。
You can do this, but the solution is relatively slow (about 22µs per call on my machine).The answer is for the C code to use C thread primitives to communicate with another goroutine that will actually run the callback.
我创建了一个围棋包提供此功能:的。
有一个例子包证明其使用的。示例说明从转到运行之外创建一个线程回调到任意转到关闭。另一个例子是。这说明一个典型的C回调接口和层在它上面一个围棋回调。
I have created a Go package that provides this functionality: rog-go.googlecode.com/hg/exp/callback.There is an example package demonstrating its use here. The example demonstrates a call back to an arbitrary Go closure from a thread created outside of the Go runtime. Another example is here. This demonstrates a typical C callback interface and layers a Go callback on top of it.
要尝试的第一个例子:
goinstall rog-go.googlecode.com/hg/exp/example/looper
cd $GOROOT/src/pkg/rog-go.googlecode.com/hg/exp/example/looper
gotest
要尝试第二个例子:
goinstall rog-go.googlecode.com/hg/exp/example/event
cd $GOROOT/src/pkg/rog-go.googlecode.com/hg/exp/example/event
gotest
这两个例子都假设pthreads的是可用的。当然,这只是一个权宜之计,直到CGO是固定的,但对于任意调用关闭围棋在C回调将适用即使在当时的技术。
Both examples assume that pthreads are available. Of course, this is just a stop-gap measure until cgo is fixed, but the technique for calling arbitrary Go closures in a C callback will be applicable even then.
下面是回调包的文档:
PACKAGE
package callback
import "rog-go.googlecode.com/hg/exp/callback"
变量
var Func = callbackFunc
Func键存放一个指针到C回调函数。
在调用时,它调用在所提供的函数f
围棋方面与给定的参数。
Func holds a pointer to the C callback function.When called, it calls the provided function f in aa Go context with the given argument.
它可以通过首先将其转换为一个函数指针被用于
然后从C主叫
下面是设置了回调函数的例子:
It can be used by first converting it to a function pointerand then calling from C.Here is an example that sets up the callback function:
//static void (*callback)(void (*f)(void*), void *arg);
//void setCallback(void *c){
// callback = c;
//}
import "C"
import "rog-go.googlecode.com/hg/exp/callback"
func init() {
C.setCallback(callback.Func)
}
这篇关于ç回调和非围棋线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!