updated the go wrapper code to save one memory allocation
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
hyung-hwan 2024-02-24 22:53:34 +09:00
parent 6b279e1785
commit ba2e5d1ed6
2 changed files with 13 additions and 5 deletions

View File

@ -13,6 +13,7 @@ import (
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
"reflect"
"sync" "sync"
"unsafe" "unsafe"
) )
@ -137,9 +138,16 @@ func hcl_go_cci_handler(c *C.hcl_t, cmd C.hcl_io_cmd_t, arg unsafe.Pointer) C.in
} }
// | fd | length | name bytes of the length | // | fd | length | name bytes of the length |
C.memcpy(tptr, unsafe.Pointer(&fd), C.size_t(unsafe.Sizeof(fd))) *(*int)(tptr) = fd;
C.memcpy(unsafe.Pointer(uintptr(tptr)+unsafe.Sizeof(fd)), unsafe.Pointer(&tlen), C.size_t(unsafe.Sizeof(tlen))) *(*C.size_t)(unsafe.Pointer(uintptr(tptr)+unsafe.Sizeof(fd))) = tlen;
C.memcpy(unsafe.Pointer(uintptr(tptr)+unsafe.Sizeof(fd)+unsafe.Sizeof(tlen)), unsafe.Pointer(C.CString(name)), tlen)
// C.CString() allocates a memory block. Use a SliceHeader to avoid extra memory allocation
// for the string conversion. Create a fake slice header that can be used with copy() instead.
var dsthdr reflect.SliceHeader
dsthdr.Data = uintptr(tptr)+unsafe.Sizeof(fd)+unsafe.Sizeof(tlen)
dsthdr.Len = int(tlen)
dsthdr.Cap = int(tlen)
copy(*(*[]byte)(unsafe.Pointer(&dsthdr)), name);
ioarg.handle = tptr ioarg.handle = tptr
return 0 return 0

View File

@ -175,12 +175,12 @@ func (hcl *HCL) SetLogTarget(target string) {
var x C.int var x C.int
var tgt *C.char var tgt *C.char
tgt = C.CString(target) tgt = C.CString(target) // TODO: need error check?
defer C.free(unsafe.Pointer(tgt)) defer C.free(unsafe.Pointer(tgt))
x = C.hcl_setoption(hcl.c, C.HCL_LOG_TARGET_BCSTR, unsafe.Pointer(tgt)) x = C.hcl_setoption(hcl.c, C.HCL_LOG_TARGET_BCSTR, unsafe.Pointer(tgt))
if x <= -1 { if x <= -1 {
// thist must not happen // this must not happen
panic(fmt.Errorf("unable to set log target - %s", hcl.get_errmsg())) panic(fmt.Errorf("unable to set log target - %s", hcl.get_errmsg()))
} }
} }