我有以下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