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()做个转换。

 

原文地址:https://www.cnblogs.com/JUSTSOSOBLOG/p/7502302.html