forked from enobufs/go-calls-c-pointer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcounter.go
42 lines (35 loc) · 1008 Bytes
/
counter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main
// typedef void (*count_cb)(int);
// extern void makeCallback(int sum, count_cb cb) {
// cb(sum);
// }
import "C"
// Above lines have nothing to do with the code below.
// It just implements the C-declaration found in
// counter_api.go. It is because counter_api.go contains
// `//export Xxx` and it will be used to generate a C header
// file `libcounter.h`. (Think of counter_api.go as a header
// file for those C code in the comment lines.)
import (
"fmt"
"time"
)
type countCb func(n int)
func count(n int, goCb countCb) int {
for i := 0; i < n; i++ {
time.Sleep(time.Second * 1)
goCb(i + 1)
}
return 0
}
// This main function won't be called when compiled as a shared
// library. But you can use it to run a quick standalone test.
// For this reason, it is recommended that a separate file be
// used for exported methods with C-types.
func main() {
fmt.Println("Running standalone..")
count(3, func(n int) {
fmt.Printf("count %d\n", n)
})
fmt.Println("done!")
}