我有以下 c++ 函数,它使用字符串设置整数。
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
extern "C" {
int a() {
int number;
string value("100");
std::istringstream strm(value);
strm >> number;
if (strm.fail()) {
cout << "Ouch!" << endl;
}
else {
cout << "Number set to:" << number << endl;
};
return (int)strm.bad();
}
}
int main(int argc, char **argv)
{
a();
}
如果我将其编译为程序,它就可以工作。
$ g++ ./streamtest.cc -o streamtest;./streamtest
Number set to:100
但是,如果我从 ctypes 调用相同的函数,它不会设置整数,并且“strm”处于“坏”状态。
$ g++ -shared streamtest.cc -o libstreamtest.so
$ python -c "import ctypes;a = ctypes.CDLL('libstreamtest.so').a();print 'Got [%s] from a()' %a"
Ouch!
Got [1] from a()
这让我很困惑。如何使此功能在 ctypes 下工作?