将字符串字面值传递给C语言

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

Passing string literal to C

问题

我正在尝试在Go语言中调用C代码。然而,当我尝试使用printf函数时,会收到一个关于格式字符串不是字符串字面值的警告:

package main

// #include <stdio.h>
import "C"

func main() {
    C.printf(C.CString("Hello world\n"));
}

警告信息如下:

警告:格式字符串不是字符串字面值(可能存在安全问题)[-Wformat-security]

我应该如何将字符串字面值传递给类似于printf的C函数?是否有类似于C.CString()的函数可以使用,还是说这是不可能的,我应该忽略这个警告?

英文:

I'm playing around with calling C code in go. When I try to use printf from go however, I get a warning about the format string not being a string literal:

package main

// #include &lt;stdio.h&gt;
import &quot;C&quot;

func main() {
    C.printf(C.CString(&quot;Hello world\n&quot;));
}

Warning:

> warning: format string is not a string literal (potentially insecure) [-Wformat-security]

How can I pass a string literal into a C function like printf? Is there a function similar to C.CString() that I can use, or is it impossible and I should ignore this warning?

答案1

得分: 2

当使用printf函数时,格式字符串最好是一个字符串字面量,而不是一个变量。而C.CString是由Go运行时转换的char指针。此外,在最新的Go版本中,你可能无法使用printf的可变参数。在其他情况下,如果你想要消除警告,请使用类型转换:

package main

/*
typedef const char* const_char_ptr;
#include <stdio.h>
*/
import "C"

func main() {
    C.puts((C.const_char_ptr)(C.CString("foo")))
}

编辑

注意为C.CString调用free函数。

package main

/*
typedef const char* const_char_ptr;
#include <stdio.h>
*/
import "C"
import "unsafe"

func main() {
    ptr := (C.const_char_ptr)(C.CString("foo"))
    defer C.free(unsafe.Pointer(ptr))
    C.puts(ptr)
}
英文:

When using printf, the format string is better to be a string literal and not a variable. And C.CString is coverted char pointer by go runtime. And also you may not use variadic arguments of printf in latest go. In other case, if you want to remove the warnings, Use type cast:

package main

/*
typedef const char* const_char_ptr;
#include &lt;stdio.h&gt;
*/
import &quot;C&quot;

func main() {
    C.puts((C.const_char_ptr)(C.CString(&quot;foo&quot;)))
}

EDIT

Note that call free for C.CString.

package main

/*
typedef const char* const_char_ptr;
#include &lt;stdio.h&gt;
*/
import &quot;C&quot;
import &quot;unsafe&quot;

func main() {
    ptr := (C.const_char_ptr)(C.CString(&quot;foo&quot;))
    defer C.free(unsafe.Pointer(ptr))
    C.puts(ptr)
}

huangapple
  • 本文由 发表于 2014年2月19日 10:16:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/21869668.html
匿名

发表评论

匿名网友

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

确定