main.go raw
1 package main
2
3 import (
4 "fmt"
5 "os"
6 "path/filepath"
7 "runtime"
8
9 "github.com/ebitengine/purego"
10 )
11
12 func main() {
13 if len(os.Args) < 2 {
14 fmt.Fprintf(os.Stderr, "usage: %s <path-to-hello.so>\n", os.Args[0])
15 os.Exit(1)
16 }
17 soPath := os.Args[1]
18 if !filepath.IsAbs(soPath) {
19 wd, _ := os.Getwd()
20 soPath = filepath.Join(wd, soPath)
21 }
22
23 lib, err := openLib(soPath)
24 if err != nil {
25 fmt.Fprintf(os.Stderr, "dlopen %s: %v\n", soPath, err)
26 os.Exit(1)
27 }
28
29 var moxieAdd func(int32, int32) int32
30 purego.RegisterLibFunc(&moxieAdd, lib, "moxie_add")
31
32 var moxieMul func(int32, int32) int32
33 purego.RegisterLibFunc(&moxieMul, lib, "moxie_mul")
34
35 // test add
36 got := moxieAdd(3, 4)
37 if got != 7 {
38 fmt.Fprintf(os.Stderr, "FAIL: moxie_add(3,4) = %d, want 7\n", got)
39 os.Exit(1)
40 }
41 fmt.Printf("PASS: moxie_add(3,4) = %d\n", got)
42
43 // test mul
44 got = moxieMul(6, 7)
45 if got != 42 {
46 fmt.Fprintf(os.Stderr, "FAIL: moxie_mul(6,7) = %d, want 42\n", got)
47 os.Exit(1)
48 }
49 fmt.Printf("PASS: moxie_mul(6,7) = %d\n", got)
50
51 // test edge: zero
52 got = moxieAdd(0, 0)
53 if got != 0 {
54 fmt.Fprintf(os.Stderr, "FAIL: moxie_add(0,0) = %d, want 0\n", got)
55 os.Exit(1)
56 }
57 fmt.Printf("PASS: moxie_add(0,0) = %d\n", got)
58
59 // test edge: negative
60 got = moxieAdd(-10, 3)
61 if got != -7 {
62 fmt.Fprintf(os.Stderr, "FAIL: moxie_add(-10,3) = %d, want -7\n", got)
63 os.Exit(1)
64 }
65 fmt.Printf("PASS: moxie_add(-10,3) = %d\n", got)
66
67 fmt.Println("\nAll roundtrip tests passed.")
68 }
69
70 func openLib(path string) (uintptr, error) {
71 switch runtime.GOOS {
72 case "linux", "darwin":
73 return purego.Dlopen(path, purego.RTLD_NOW|purego.RTLD_GLOBAL)
74 default:
75 return 0, fmt.Errorf("unsupported OS: %s", runtime.GOOS)
76 }
77 }
78