我有以下C++函數使用字符串設置整數。爲什麼這個extern「C」函數不能用python ctypes工作?
#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下工作?
會不會是蟒蛇庫加載程序沒有正確調用由標準庫的流需要一些全局/靜態構造函數? – 2012-02-29 16:21:19
您是否嘗試過單步調試和比較他們開始偏離的位置? – PlasmaHH 2012-02-29 16:26:29
確strm有錯誤的功能? (一個在strm.fail()後打印錯誤) – KevinDTimm 2012-02-29 16:28:47