英文:
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])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论