-
Notifications
You must be signed in to change notification settings - Fork 3
/
ffi.go
74 lines (60 loc) · 1.32 KB
/
ffi.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
package main
// $ go build -buildmode=c-archive -o glitch.a ffi.go
/*
#include <stdlib.h>
typedef struct {
char *data;
size_t size;
} Image_t;
*/
import "C"
import (
"image"
"image/png"
_ "image/jpeg"
"bytes"
"unsafe"
"github.com/sug0/go-glitch"
)
// this does nothing...
func main() {}
//export jumble_pixels
func jumble_pixels(expression, data *C.char, size C.int) *C.Image_t {
// compile expression
expr, err := glitch.CompileExpression(C.GoString(expression))
if err != nil {
return nil
}
// write the raw image data to a bytes.Buffer
buf := new(bytes.Buffer)
if _,err := buf.Write(C.GoBytes(unsafe.Pointer(data), size)); err != nil {
return nil
}
// decode image from bytes.Buffer
img, _, err := image.Decode(buf)
if err != nil {
return nil
}
// glitch that shit
glitchedimg, err := expr.JumblePixels(img)
if err != nil {
return nil
}
// encode to a png
img = nil
buf.Reset()
if err := png.Encode(buf, glitchedimg); err != nil {
return nil
}
// return raw image data
b := buf.Bytes()
l := C.size_t(len(b))
m := C.malloc(l)
if m == nil {
return nil
}
s := (*C.Image_t)(m)
s.size = l
s.data = (*C.char)(C.CBytes(b))
return s
}