C++ that creates string:
#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();
}
}
Python code that should return string generated in C++:
from ctypes import cdll
lib = cdll.LoadLibrary('mylib.so')
print(lib.getchars())
And it returns different numbers like 18806352, What should I do to return normal string? In C++ This functions works well
string getcharsshould bechar *getchars, since that's whatc_str()returns.c_str()becomes invalid when thestd::stringis destroyed. Sinceoutputis destroyed when the function returns, you can't returnoutput.c_str().output.c_str()to it, then return that pointer.