文字列を使用して整数を設定する次の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で機能させるにはどうすればよいですか?