Passing array of string as parameter from go to C function

感情迁移 提交于 2019-12-31 03:43:14

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/45997786/passing-array-of-string-as-parameter-from-go-to-c-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!