Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>I have created a Go package that provides this functionality: <a href="http://code.google.com/p/rog-go/source/browse/exp/callback/" rel="nofollow">rog-go.googlecode.com/hg/exp/callback</a>. There is an example package demonstrating its use <a href="http://code.google.com/p/rog-go/source/browse/exp/example/looper/looper.go" rel="nofollow">here</a>. The example demonstrates a call back to an arbitrary Go closure from a thread created outside of the Go runtime. Another example is <a href="http://code.google.com/p/rog-go/source/browse/exp/example/event" rel="nofollow">here</a>. This demonstrates a typical C callback interface and layers a Go callback on top of it.</p> <p>To try out the first example:</p> <pre><code>goinstall rog-go.googlecode.com/hg/exp/example/looper cd $GOROOT/src/pkg/rog-go.googlecode.com/hg/exp/example/looper gotest </code></pre> <p>To try out the second example:</p> <pre><code>goinstall rog-go.googlecode.com/hg/exp/example/event cd $GOROOT/src/pkg/rog-go.googlecode.com/hg/exp/example/event gotest </code></pre> <p>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.</p> <p>Here is the documentation for the callback package:</p> <p><strong>PACKAGE</strong></p> <pre><code>package callback import "rog-go.googlecode.com/hg/exp/callback" </code></pre> <p><strong>VARIABLES</strong></p> <pre><code>var Func = callbackFunc </code></pre> <p>Func holds a pointer to the C callback function. When called, it calls the provided function f in a a Go context with the given argument.</p> <p>It can be used by first converting it to a function pointer and then calling from C. Here is an example that sets up the callback function:</p> <pre><code>//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) } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload