【发布时间】:2017-07-17 17:17:52
【问题描述】:
我想将字符串变量的数据指针(如 c++ 中的 string::c_str())传递给 c 函数,但我发现这不起作用:
package main
/*
#include <stdio.h>
void Println(const char* str) {printf("%s\n", str);}
*/
import "C"
import (
"unsafe"
)
func main() {
s := "hello"
C.Println((*C.char)(unsafe.Pointer(&(s[0]))))
}
编译错误信息是:'cannot take the address of s[0]'。 这没关系,但我怀疑它会导致不必要的内存应用。有没有更好的方法来获取数据指针?
C.Println((*C.char)(unsafe.Pointer(&([]byte(s)[0]))))
【问题讨论】: