python c++ 混合編程中python調用c++string返回類型的函數,python中返回為數字的解決辦法


本隨筆解決 Python使用ctypes 調用c++dll 字符串返回類型函數,在python中顯示為數字;原文解決方案見so:

https://stackoverflow.com/questions/12500069/ctypes-how-to-pass-string-from-python-to-c-function-and-how-to-return-string/12500326#12500326

解決方案如下:

1.      據說無關pythonctypes的事。

2.      C++定義導出函數的時候,需要使用const char *,而不能使用string返回類型,如:

extern "C"

const char *return_string(char* name){

    cout<<strlen(name)<<endl;

    cout<<name<<endl;

    static string s = "hello ";

    s += name;

    return s.c_str();

}

3.      上面的函數定義也看到了,在函數體中使用string臨時變量的話,需要static string str這樣的形式定義,聲明為靜態變量。

4.      string類型臨時變量賦值的時候,必須使用+=,而不是=

 

5.      最后往出傳遞的話,使用s.c_str()做個轉換。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM