-
Notifications
You must be signed in to change notification settings - Fork 3
/
example_c_iovec_test.go
43 lines (36 loc) · 984 Bytes
/
example_c_iovec_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package ptrguard_test
import (
"fmt"
"math"
"github.com/ansiwen/ptrguard"
C "github.com/ansiwen/ptrguard/internal/testhelper"
)
// Example how to use PtrGuard with a C allocated iovec array.
func Example_cAllocatedIovec() {
var buffers [][]byte
for i := 2; i < 12; i += 3 {
buffers = append(buffers, make([]byte, i))
}
numberOfBuffers := len(buffers)
cPtr := C.Malloc(C.SizeOfIovec * uintptr(len(buffers)))
defer C.Free(cPtr)
// This is a trick to create a slice on top of the C allocated array, for
// easier and safer access.
iovec := (*[math.MaxInt32]C.Iovec)(cPtr)[:numberOfBuffers:numberOfBuffers]
var pinner ptrguard.Pinner
defer pinner.Unpin()
for i := range iovec {
bufferPtr := &buffers[i][0]
pinner.Pin(bufferPtr).Store(&iovec[i].Base)
iovec[i].Len = C.Int(len(buffers[i]))
}
C.FillBuffersWithX(&iovec[0], len(iovec))
for i := range buffers {
fmt.Println(string(buffers[i]))
}
// Output:
// XX
// XXXXX
// XXXXXXXX
// XXXXXXXXXXX
}