-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathexample_test.go
More file actions
71 lines (57 loc) · 1.7 KB
/
example_test.go
File metadata and controls
71 lines (57 loc) · 1.7 KB
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
package ffi_test
import (
"fmt"
"math"
"unsafe"
"github.com/jupiterrider/ffi"
)
func ExamplePrepClosureLoc() {
// This example recreates a well-known math function and then calls it.
var sin unsafe.Pointer
closure := ffi.ClosureAlloc(unsafe.Sizeof(ffi.Closure{}), &sin)
defer ffi.ClosureFree(closure)
fun := ffi.NewCallback(func(cif *ffi.Cif, ret unsafe.Pointer, args *unsafe.Pointer, userData unsafe.Pointer) uintptr {
arg := unsafe.Slice(args, cif.NArgs)[0]
sine := math.Sin(*(*float64)(arg))
*(*float64)(ret) = sine
return 0
})
var cif ffi.Cif
if status := ffi.PrepCif(&cif, ffi.DefaultAbi, 1, &ffi.TypeDouble, &ffi.TypeDouble); status != ffi.OK {
panic(status)
}
// sin becomes a C function pointer with the following signature:
// double sin(double x);
if status := ffi.PrepClosureLoc(closure, &cif, fun, nil, sin); status != ffi.OK {
panic(status)
}
sine, x := 0.0, 1.0
ffi.Call(&cif, uintptr(sin), unsafe.Pointer(&sine), unsafe.Pointer(&x))
fmt.Println(sine)
// Output: 0.8414709848078965
}
func ExampleGetStructOffsets() {
type example struct {
b byte
f float32
b2 byte
i int32
}
exampleType := ffi.NewType(&ffi.TypeUint8, &ffi.TypeFloat, &ffi.TypeUint8, &ffi.TypeSint32)
var offsets [4]uint64
if status := ffi.GetStructOffsets(ffi.DefaultAbi, &exampleType, &offsets[0]); status != ffi.OK {
panic(status)
}
var e example
fmt.Println(uint64(unsafe.Sizeof(e)) == exampleType.Size)
fmt.Println(uint64(unsafe.Offsetof(e.b)) == offsets[0])
fmt.Println(uint64(unsafe.Offsetof(e.f)) == offsets[1])
fmt.Println(uint64(unsafe.Offsetof(e.b2)) == offsets[2])
fmt.Println(uint64(unsafe.Offsetof(e.i)) == offsets[3])
// Output:
// true
// true
// true
// true
// true
}