Skip to content

Commit

Permalink
objc: add safe Objc Classes (#160)
Browse files Browse the repository at this point in the history
Closes #143
  • Loading branch information
TotallyGamerJet authored Sep 9, 2023
1 parent 0f25ec6 commit 6319229
Show file tree
Hide file tree
Showing 4 changed files with 246 additions and 233 deletions.
62 changes: 30 additions & 32 deletions examples/objc/main_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ package main

import (
"fmt"
"unsafe"
"reflect"

"github.com/ebitengine/purego/objc"
)
Expand All @@ -17,45 +17,43 @@ var (
sel_bar = objc.RegisterName("bar")
)

type barObject struct {
isa objc.Class `objc:"BarObject : NSObject <NSDelegateWindow>"`
bar int
}

func (b *barObject) Init(_cmd objc.SEL) objc.ID {
return objc.ID(unsafe.Pointer(b)).SendSuper(_cmd)
}

func (b *barObject) Bar(_cmd objc.SEL) int {
return b.bar
}

func (b *barObject) SetBar(_cmd objc.SEL, bar int) {
b.bar = bar
}

func (_ *barObject) Selector(metName string) objc.SEL {
switch metName {
case "Init":
return sel_init
case "SetBar":
return sel_setBar
case "Bar":
return sel_bar
default:
return 0
}
func BarInit(id objc.ID, cmd objc.SEL) objc.ID {
return id.SendSuper(cmd)
}

func main() {
class, err := objc.RegisterClass(&barObject{})
// This struct is equivalent to the following Objective-C definition.
//
// @interface BarObject : NSObject <NSDelegateWindow>
// @property (readwrite) bar int
// @end
class, err := objc.RegisterClass(
"BarObject",
objc.GetClass("NSObject"),
[]*objc.Protocol{
objc.GetProtocol("NSDelegateWindow"),
},
[]objc.FieldDef{
{
Name: "bar",
Type: reflect.TypeOf(int(0)),
Attribute: objc.ReadWrite,
},
},
[]objc.MethodDef{
{
Cmd: sel_init,
Fn: BarInit,
},
},
)
if err != nil {
panic(err)
}

var object = objc.ID(class).Send(sel_new)
object := objc.ID(class).Send(sel_new)
object.Send(sel_setBar, 123)
var bar = int(object.Send(sel_bar))
bar := int(object.Send(sel_bar))
fmt.Println(bar)
// Output: 123
}
4 changes: 2 additions & 2 deletions internal/strings/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ func CString(name string) *byte {
if hasSuffix(name, "\x00") {
return &(*(*[]byte)(unsafe.Pointer(&name)))[0]
}
var b = make([]byte, len(name)+1)
b := make([]byte, len(name)+1)
copy(b, name)
return &b[0]
}

// GoString copies a char* to a Go string.
// GoString copies a null-terminated char* to a Go string.
func GoString(c uintptr) string {
// We take the address and then dereference it to trick go vet from creating a possible misuse of unsafe.Pointer
ptr := *(*unsafe.Pointer)(unsafe.Pointer(&c))
Expand Down
Loading

0 comments on commit 6319229

Please sign in to comment.