【发布时间】:2020-06-12 07:32:24
【问题描述】:
创建字符串的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++ 中这个函数很好用
【问题讨论】:
-
string getchars应该是char *getchars,因为这是c_str()返回的内容。 -
@Barmar 这将返回一个指向本地的指针。
-
c_str()返回的字符串在std::string被销毁后失效。由于函数返回时output被销毁,所以不能返回output.c_str()。 -
我认为您需要分配一个动态 C 字符串并将
output.c_str()复制到其中,然后返回该指针。 -
@Barmar 我不知道该怎么做,如果你写一点代码我会很感激我怎么做以及为什么