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