[英]Passing string literal to C
我正在玩中調用C代碼。 當我嘗試使用printf
時,我得到一個關於格式字符串不是字符串文字的警告:
package main
// #include <stdio.h>
import "C"
func main() {
C.printf(C.CString("Hello world\n"));
}
警告:
警告:格式字符串不是字符串文字(可能不安全)[-Wformat-security]
如何將字符串文字傳遞給像printf
這樣的C函數? 我可以使用類似於C.CString()
的函數,還是不可能,我應該忽略這個警告?
使用printf時,格式字符串最好是字符串文字而不是變量。 並且C.CString是運行時轉換的char指針。 而且你也許不會在最新的go中使用printf的variadic參數。 在其他情況下,如果要刪除警告,請使用類型轉換:
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免費調用。
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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.