Passing array of string as parameter from go to C function

后端 未结 1 1963
孤城傲影
孤城傲影 2021-01-25 00:31

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 la

相关标签:
1条回答
  • 2021-01-25 00:47

    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

    0 讨论(0)
提交回复
热议问题