Skip to content

Commit 1aee0eb

Browse files
cosmo0920edsiper
authored andcommitted
Reflect description for C.malloc implementation
Signed-off-by: Hiroshi Hatake <[email protected]>
1 parent 4b7be6a commit 1aee0eb

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

examples/in_gdummy/README.md

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -51,17 +51,26 @@ The callback will send a raw buffer of msgpack data with it proper bytes length
5151
```go
5252
import "reflect" // Import reflect package.
5353

54-
// Operate safe payload creation.
55-
func MakePayload(packed []byte) (**C.void, int) {
56-
var payload **C.void
54+
func alloc(size int) unsafe.Pointer {
55+
return C.calloc(C.size_t(size), 1)
56+
}
5757

58-
length := len(packed)
59-
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&payload))
60-
hdr.Data = uintptr(unsafe.Pointer(&packed))
61-
hdr.Len = length
58+
func makeSlice(p unsafe.Pointer, n int) *Slice {
59+
data := &c_slice_t{p, n}
60+
61+
runtime.SetFinalizer(data, func(data *c_slice_t){
62+
C.free(data.p)
63+
})
64+
65+
s := &Slice{data: data}
66+
h := (*reflect.SliceHeader)(unsafe.Pointer(&s.Data))
67+
h.Data = uintptr(p)
68+
h.Len = n
69+
h.Cap = n
6270

63-
return payload, length
71+
return s
6472
}
73+
6574
//export FLBPluginInputCallback
6675
func FLBPluginInputCallback(data **C.void, size *C.size_t) int {
6776
now := time.Now()
@@ -74,9 +83,11 @@ func FLBPluginInputCallback(data **C.void, size *C.size_t) int {
7483
// Some encoding logs to msgpack payload stuffs.
7584
// It needs to Wait for some period on Golang input plugin side, until the new records are emitted.
7685

77-
payload, length := MakePayload(packed)
78-
79-
*data = *payload
86+
length := len(packed)
87+
p := alloc(length)
88+
s := makeSlice(p, length)
89+
copy(s.Data, packed)
90+
*data = unsafe.Pointer(&s.Data[0])
8091
*size = C.size_t(len(packed))
8192
return input.FLB_OK
8293
}

0 commit comments

Comments
 (0)