-
Notifications
You must be signed in to change notification settings - Fork 76
/
util.go
95 lines (77 loc) · 1.93 KB
/
util.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved.
// Use of this source code is governed by a LGPLv2.1
// license that can be found in the LICENSE file.
//go:build linux && cgo
// +build linux,cgo
package lxc
/*
#include <stdlib.h>
#include <lxc/lxccontainer.h>
static char** makeCharArray(size_t size) {
// caller checks return value
return calloc(size, sizeof(char*));
}
static void setArrayString(char **array, char *string, size_t n) {
array[n] = string;
}
static void freeCharArray(char **array, size_t size) {
size_t i;
for (i = 0; i < size; i++) {
free(array[i]);
}
free(array);
}
static void freeSnapshotArray(struct lxc_snapshot *s, size_t size) {
size_t i;
for (i = 0; i < size; i++) {
s[i].free(&s[i]);
}
free(s);
}
static size_t getArrayLength(char **array) {
char **p;
size_t size = 0;
for (p = (char **)array; *p; p++) {
size++;
}
return size;
}
*/
import "C"
import (
"unsafe"
)
func makeNullTerminatedArgs(args []string) **C.char {
cparams := C.makeCharArray(C.size_t(len(args) + 1))
if cparams == nil {
return nil
}
for i := 0; i < len(args); i++ {
C.setArrayString(cparams, C.CString(args[i]), C.size_t(i))
}
C.setArrayString(cparams, nil, C.size_t(len(args)))
return cparams
}
func freeNullTerminatedArgs(cArgs **C.char, length int) {
C.freeCharArray(cArgs, C.size_t(length+1))
}
func convertArgs(cArgs **C.char) []string {
if cArgs == nil {
return nil
}
return convertNArgs(cArgs, int(C.getArrayLength(cArgs)))
}
func convertNArgs(cArgs **C.char, size int) []string {
if cArgs == nil || size <= 0 {
return nil
}
tmpslice := (*[(1 << 29) - 1]*C.char)(unsafe.Pointer(cArgs))[:size:size]
result := make([]string, size)
for i, s := range tmpslice {
result[i] = C.GoString(s)
}
return result
}
func freeSnapshots(snapshots *C.struct_lxc_snapshot, size int) {
C.freeSnapshotArray(snapshots, C.size_t(size))
}