英文:
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 <stdio.h>
import "C"
func main() {
C.printf(C.CString("Hello world\n"));
}
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 <stdio.h>
*/
import "C"
func main() {
C.puts((C.const_char_ptr)(C.CString("foo")))
}
EDIT
Note that call free for C.CString.
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论