将Go的[]string转换为C的char**。

huangapple go评论84阅读模式
英文:

Go []string to C char**

问题

我开始尝试在我的Go代码中使用cgo将一些C库集成进来,但遇到了一个问题。

在其中一个C函数中,我需要将argv传递给一个函数调用。在C中,argv是一个指向char字符串数组的指针(K&R C,§5.10),我需要将其从字符串切片转换为char**。

我已经仔细查找了关于如何在Go和C之间进行变量类型转换的任何信息,但几乎没有文档。任何帮助将不胜感激。

英文:

I started trying to integrate some C libraries into my Go code for a project using cgo and have come across a problem.

In one of the C functions I need to pass argv to a function call. In C argv is a pointer to an array of char strings (K&R C, §5.10) and I need to convert from a slice of strings to a char**.

I have had a good look, high and low for any information on how to do variable type conversions from Go to C but there appears to be next to no documentation. Any help would be appreciated.

答案1

得分: 8

你需要自己创建数组。可以使用以下代码:

argv := make([]*C.char, len(args))
for i, s := range args {
    cs := C.CString(s)
    defer C.free(unsafe.Pointer(cs))
    argv[i] = cs
}
C.foo(&argv[0])
英文:

You'll need to create the array yourself. Something like this should do:

argv := make([]*C.char, len(args))
for i, s := range args {
    cs := C.CString(s)
    defer C.free(unsafe.Pointer(cs))
    argv[i] = cs
}
C.foo(&argv[0])

huangapple
  • 本文由 发表于 2014年1月16日 17:39:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/21158126.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定