[Python中的C ++函数返回数字而不是字符串

问题描述 投票:0回答:1

创建字符串的C ++:

#include <iostream>
#include <string>

using namespace std;

extern "C" {
    string getchars() {
        string output = "";
        char letters[4] = { 'A', 'G', 'T', 'C' };
        for (int i = 0; i < 10000000; i++) {
            output += letters[rand() % 4];
        }
        return output.c_str();
    }

}

应该返回在C ++中生成的字符串的Python代码:

from ctypes import cdll
lib = cdll.LoadLibrary('mylib.so')
print(lib.getchars())

它返回不同的数字,例如18806352,我应该怎么做才能返回普通字符串?在C ++中,此功能运行良好]

python c++
1个回答
0
投票

您需要返回一个C字符串,而不是C ++ std::string。您需要为c_str()制作一个动态副本,以便它的生命周期超过创建它的函数。

extern "C" {
    char * getchars() {
        string output = "";
        char letters[4] = { 'A', 'G', 'T', 'C' };
        for (int i = 0; i < 10000000; i++) {
            output += letters[rand() % 4];
        }
        return strdup(output.c_str());
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.