【问题标题】:python string uses special characters to send to c++ dll, crashespython字符串使用特殊字符发送到c++ dll,崩溃
【发布时间】:2012-07-25 01:01:53
【问题描述】:

我有一个调用 c++ dll 方法的 python 方法,其中包含 printf()。

典型通话:

method ("something")

但现在我必须能够调用类似的东西

method("%x %y %z")

它正在崩溃。

我已经逃过了%,很简单

if msg:            
    msg = msg.replace( "%", "/%" )

它似乎适用于只有一个的情况。 (不知道具体对文字本身有什么影响……)

所以我测试了不止一个,我得到了一个 Debug Assertion Failure - Expression ("Incorrect format specifier", 0)。

编辑:接受答案后,解决方案:

if msg:            
   msg = msg.replace( "%", "%%" )

【问题讨论】:

    标签: c++ python dll special-characters


    【解决方案1】:

    反斜杠是转义字符。试试这个:

    if msg:            
      msg = msg.replace( "%", "\%" )
    

    您的无效格式说明符错误来自%z or %y not begin valid tokens。


    您正在尝试做的事情有点令人困惑。据我所知,您正在尝试这样做:

    // Insert your string elements in python, before calling C functions.
    method("%s %s %s" % ("Hello", "python", "world!")
    

    或者这个:

    // Set the string format in python and pass to C function
    method("%%s %%s %%s")
    
    // In C function
    char buf[128];
    // Print your string with your custom format.
    printf(GetStringFormatFromPython(), "Hello", "python", "world!");
    

    【讨论】:

    • 对不起,我复制错了,这就是我的代码(反斜杠)
    • 好的。好吧,我认为 Ignacio 对printf 令牌有一个很好的看法。您是要插入到您的字符串 python 端,还是在 c++ 中?因为这些标记在 c++ 中仍然无效。
    • 谢谢。我会测试,到目前为止,我已经修改了我的 python 并让它运行,但我想在 c++ 中做一些事情,这样 python 可以做它想做的任何事情。感谢您的帮助。
    【解决方案2】:

    sprintf() 等中转义百分号的方法是将它们加倍(即%%)。但是代码本身需要通过使用"%s"作为第一个参数而不是传递的字符串来修复。

    【讨论】:

    • 我认为这是我需要的——但在哪里?而不是 const char ?
    • sprintf("%s", variable_passed_in);
    • 我做了:“char new_msg[80]; sprintf(new_msg, "%%s", msg);"我得到了“%s”。这是正确的方法,不是吗?
    • 你已经逃脱了“%s”中的“%”。你不能那样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多