gpt4 book ai didi

pointers - 如何在 go 中获取字符串变量的数据指针?

转载 作者:数据小太阳 更新时间:2023-10-29 03:05:14 25 4
gpt4 key购买 nike

我想获取一个字符串变量的数据指针(如 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]))))
}

编译错误信息是:“无法获取 s[0] 的地址”。这没问题,但我怀疑它会导致不必要的内存应用。有没有更好的方法获取数据指针?

C.Println((*C.char)(unsafe.Pointer(&([]byte(s)[0]))))

最佳答案

有一些方法可以在不复制的情况下将底层数据从 Go 字符串获取到 C。它不能用作 C 字符串,因为它不是 C 字符串。即使您设法提取指针,即使它有时会工作,您的 printf 也不会工作。 Go 字符串不是 C 字符串。当 Go 使用更多 libc 时,它们曾经是为了兼容性,现在不再是了。

只需按照 cgo 手册使用 C.CString。如果您正在为效率而战,您将通过不使用 cgo 赢得更多,因为调用 C 的开销比分配一些内存和复制字符串要大得多。

关于pointers - 如何在 go 中获取字符串变量的数据指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42479895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com