Passing a string literal in C

I play with calling C code in go. However, when I try to use printffrom go, I get a warning that the format string is not a string literal:

package main

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

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

Attention:

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

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

+4
source share
1 answer

printf , . C.CString char run runtime. printf . , , 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")))
}

, 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)
}
+2

Source: https://habr.com/ru/post/1527622/


All Articles