File: util.go

package info (click to toggle)
golang-gopkg-lxc-go-lxc.v2 0.0+git20190625.f4822c6-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 404 kB
  • sloc: ansic: 500; makefile: 81
file content (105 lines) | stat: -rw-r--r-- 2,171 bytes parent folder | download | duplicates (2)
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
96
97
98
99
100
101
102
103
104
105
// 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.

// +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 (
	"reflect"
	"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
	}

	var A []*C.char

	hdr := reflect.SliceHeader{
		Data: uintptr(unsafe.Pointer(cArgs)),
		Len:  size,
		Cap:  size,
	}
	cArgsInterface := reflect.NewAt(reflect.TypeOf(A), unsafe.Pointer(&hdr)).Elem().Interface()

	result := make([]string, size)
	for i := 0; i < size; i++ {
		result[i] = C.GoString(cArgsInterface.([]*C.char)[i])
	}
	C.freeCharArray(cArgs, C.size_t(size))

	return result
}

func freeSnapshots(snapshots *C.struct_lxc_snapshot, size int) {
	C.freeSnapshotArray(snapshots, C.size_t(size))
}