doushi9780 2014-02-19 02:16
浏览 89
已采纳

将字符串文字传递给C

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
"));
}

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条回答 默认 最新

  • dongshi1148 2014-02-19 06:55
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突