2

I have one C function:

int cgroup_change_cgroup_path(const char * path, pid_t pid, const char *const  controllers[])

I want to call it in go language by using cgo. How to pass the third parameter as it accepts a C array of string.

Sven
  • 5,155
  • 29
  • 53

1 Answers1

3

You can build the arrays using c helper functions and then use them.

Here is a solution to the same problem:

// C helper functions:

static char**makeCharArray(int size) {
        return calloc(sizeof(char*), size);
}

static void setArrayString(char **a, char *s, int n) {
        a[n] = s;
}

static void freeCharArray(char **a, int size) {
        int i;
        for (i = 0; i < size; i++)
                free(a[i]);
        free(a);
}

// Build C array in Go from sargs []string

cargs := C.makeCharArray(C.int(len(sargs)))
defer C.freeCharArray(cargs, C.int(len(sargs)))
for i, s := range sargs {
        C.setArrayString(cargs, C.CString(s), C.int(i))
}

golangnuts post by John Barham

Kenny Grant
  • 9,360
  • 2
  • 33
  • 47