-
Notifications
You must be signed in to change notification settings - Fork 2
/
io_c.go
107 lines (96 loc) · 2.46 KB
/
io_c.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package gogd
// #include <gd.h>
// #cgo LDFLAGS: -lgd
import "C"
import "log"
import "reflect"
import "unsafe"
import "os"
import "io"
type gdio interface{}
//export gogd_get_c
func gogd_get_c(ctx *C.gdIOCtx) int {
gdio := (*(*gdio)(ctx.data))
buf := make([]byte, 1)
_, err := gdio.(io.Reader).Read(buf)
if err != nil && err != io.EOF {
log.Println(err)
}
return int(buf[0])
}
//export gogd_get_buf
func gogd_get_buf(ctx *C.gdIOCtx, cbuf unsafe.Pointer, l C.int) int {
gdio := (*(*gdio)(ctx.data))
buf := goSliceFromcString((*C.char)(cbuf), int(l))
n, err := gdio.(io.Reader).Read(buf)
if err != nil && err != io.EOF {
log.Println(err)
return 0
}
return n
}
//export gogd_put_buf
func gogd_put_buf(ctx *C.gdIOCtx, cbuf unsafe.Pointer, l C.int) int {
gdio := (*(*gdio)(ctx.data))
buf := goSliceFromcString((*C.char)(cbuf), int(l))
n, err := gdio.(io.Writer).Write(buf)
if err != nil {
log.Println(err)
return 0
}
return n
}
//export gogd_put_c
func gogd_put_c(ctx *C.gdIOCtx, c int) {
gdio := (*(*gdio)(ctx.data))
buf := []byte{byte(c)}
_, err := gdio.(io.Writer).Write(buf)
if err != nil {
log.Println(err)
}
}
//export gogd_seek
func gogd_seek(ctx *C.gdIOCtx, c int) int {
gdio := (*(*gdio)(ctx.data))
n, err := gdio.(io.Seeker).Seek(int64(c), 0)
if err != nil {
log.Println(err)
}
return int(n)
}
//export gogd_tell
func gogd_tell(ctx *C.gdIOCtx) int {
gdio := (*(*gdio)(ctx.data))
n, err := gdio.(io.Seeker).Seek(int64(os.SEEK_CUR), 0)
if err != nil {
log.Println(err)
}
return int(n)
}
// goSliceFromcString provides a zero copy interface for returning a go slice backed by a c array.
func goSliceFromcString(cArray *C.char, size int) []byte {
//See http://code.google.com/p/go-wiki/wiki/cgo
//It turns out it's really easy to
//make a string from a *C.char and vise versa.
//not so easy to write to a c array.
var sliceHeader reflect.SliceHeader
sliceHeader.Cap = size
sliceHeader.Len = size
sliceHeader.Data = uintptr(unsafe.Pointer(cArray))
return *(*[]byte)(unsafe.Pointer(&sliceHeader))
}
// goSliceFromcString provides a zero copy interface for returning a go slice backed by a c array.
func goSliceFromcStringNull(cArray *C.char) []byte {
c := cArray
count := 0
for *c != 0 {
c = (*C.char)(unsafe.Pointer(uintptr(unsafe.Pointer(c)) + 8))
count++
}
return goSliceFromcString(cArray, count)
}
//export gogd_error
func gogd_error(c C.int, msg *C.char, l unsafe.Pointer) {
s := goSliceFromcStringNull(msg)
log.Println(string(s))
}