[英]python string uses special characters to send to c++ dll, crashes
我有一個python方法調用c ++ dll方法,其中包含printf()。
典型電話:
method ("something")
但是現在我必須能夠打電話
method("%x %y %z")
而且它崩潰了。
我用一個非常簡單的方法逃脫了%
if msg:
msg = msg.replace( "%", "/%" )
它似乎只適用於只有一個的情況。 (不知道它對文本本身有什么影響...)
因此,我進行了不止一次的測試,並且得到了“調試斷言失敗-表達式”(“格式不正確的說明符”,0)。
編輯:接受答案后,解決方案:
if msg:
msg = msg.replace( "%", "%%" )
反斜杠是轉義字符。 嘗試這個:
if msg:
msg = msg.replace( "%", "\%" )
您無效的格式說明符錯誤是由於%z or %y
沒有開始有效的令牌引起的。
您正在嘗試做的事情有點令人困惑。 據我所知,您正在嘗試執行以下任一操作:
// 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!");
在sprintf()
等中轉義百分號的方法是將它們加倍(即%%
)。 但是代碼本身需要通過使用"%s"
(而不是傳遞的字符串)作為第一個參數來進行固定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.