golang-ui / nuklear

This project provides Go bindings for nuklear.h — a small ANSI C GUI library.
https://github.com/vurtun/nuklear
MIT License
1.57k stars 98 forks source link

NkEditString doesn't update the buffer length #31

Open tbogdala opened 6 years ago

tbogdala commented 6 years ago

When calling nk.NkEditString (or NkEditStringZeroTerminated) the nuklear wrapper will send the underlying slice Data out to C, but it never updates the length of the buffer. So if the user edits the string in the editbox, the buffer that the Go code has will always have the same length and won't update properly.

A quick hack that I created to get around the problem is to wrap the function and return a new string from the buffer (which could be improved to only create the string when necessary, but this was just a proof of concept).

func editString(ctx *nk.Context, flags nk.Flags, bufferStr string, filter nk.PluginFilter) (string, nk.Flags) {
    const extraBuffer = 64
    len := int32(len(bufferStr))
    max := len + extraBuffer
    haxBuffer := make([]byte, 0, max)
    haxBuffer = append(haxBuffer, bufferStr...)

    retflags := nk.NkEditStringZeroTerminated(ctx, flags, haxBuffer, max, filter)
    rawData := (*C.char)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&haxBuffer)).Data))
    return C.GoString(rawData), retflags
}
wilyarti commented 6 years ago

I did a work around for this. Create a fixed buffer length and trim the null bytes.

See my code: github.com/wilyarti/hashtree-ui

You can also pass a pointer to the buffer and update it that way.