从C函数传递字符串数组作为参数 [英] Passing array of string as parameter from go to C function

查看:2303
本文介绍了从C函数传递字符串数组作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C函数:

I have one C function:

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

我想用cgo通过go语言调用它。
如何传递第三个参数,因为它接受C数组的字符串。

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.

推荐答案

c帮助程序的功能,然后使用它们。

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 发布通过John Barham

golangnuts post by John Barham

这篇关于从C函数传递字符串数组作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆