1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: 2023 The Ebitengine Authors
3
4//go:build darwin || linux
5
6package purego_test
7
8import (
9 "fmt"
10 "runtime"
11 "testing"
12 "unsafe"
13
14 "github.com/ebitengine/purego"
15)
16
17func getSystemLibrary() (string, error) {
18 switch runtime.GOOS {
19 case "darwin":
20 return "/usr/lib/libSystem.B.dylib", nil
21 case "linux":
22 return "libc.so.6", nil
23 default:
24 return "", fmt.Errorf("GOOS=%s is not supported", runtime.GOOS)
25 }
26}
27
28func TestRegisterFunc(t *testing.T) {
29 library, err := getSystemLibrary()
30 if err != nil {
31 t.Errorf("couldn't get system library: %s", err)
32 }
33 libc, err := purego.Dlopen(library, purego.RTLD_NOW|purego.RTLD_GLOBAL)
34 if err != nil {
35 t.Errorf("failed to dlopen: %s", err)
36 }
37 var puts func(string)
38 purego.RegisterLibFunc(&puts, libc, "puts")
39 puts("Calling C from from Go without Cgo!")
40}
41
42func ExampleNewCallback() {
43 if runtime.GOOS == "linux" {
44 // TODO: enable once callbacks are working properly on Linux
45 fmt.Println("1 2 3 4 5 6 7 8 9\n45")
46 return
47 }
48
49 cb := purego.NewCallback(func(a1, a2, a3, a4, a5, a6, a7, a8, a9 int) int {
50 fmt.Println(a1, a2, a3, a4, a5, a6, a7, a8, a9)
51 return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9
52 })
53
54 var fn func(a1, a2, a3, a4, a5, a6, a7, a8, a9 int) int
55 purego.RegisterFunc(&fn, cb)
56
57 ret := fn(1, 2, 3, 4, 5, 6, 7, 8, 9)
58 fmt.Println(ret)
59
60 //Output: 1 2 3 4 5 6 7 8 9
61 // 45
62}
63
64func Test_qsort(t *testing.T) {
65 if runtime.GOOS == "linux" {
66 // TODO: enable once callbacks are working properly on Linux
67 t.SkipNow()
68 }
69
70 library, err := getSystemLibrary()
71 if err != nil {
72 t.Errorf("couldn't get system library: %s", err)
73 }
74 libc, err := purego.Dlopen(library, purego.RTLD_NOW|purego.RTLD_GLOBAL)
75 if err != nil {
76 t.Errorf("failed to dlopen: %s", err)
77 }
78
79 var data = []int{88, 56, 100, 2, 25}
80 var sorted = []int{2, 25, 56, 88, 100}
81 compare := func(a, b *int) int {
82 return *a - *b
83 }
84 var qsort func(data []int, nitms uintptr, size uintptr, compar func(a, b *int) int)
85 purego.RegisterLibFunc(&qsort, libc, "qsort")
86 qsort(data, uintptr(len(data)), unsafe.Sizeof(int(0)), compare)
87 for i := range data {
88 if data[i] != sorted[i] {
89 t.Errorf("got %d wanted %d at %d", data[i], sorted[i], i)
90 }
91 }
92}