2012-02-29 92 views
2

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

+0

會不會是蟒蛇庫加載程序沒有正確調用由標準庫的流需要一些全局/靜態構造函數? – 2012-02-29 16:21:19

+0

您是否嘗試過單步調試和比較他們開始偏離的位置? – PlasmaHH 2012-02-29 16:26:29

+1

確strm有錯誤的功能? (一個在strm.fail()後打印錯誤) – KevinDTimm 2012-02-29 16:28:47

回答

1

它適用於使用x86構建的Windows 7(x64)。你有沒有嘗試用C包裝代碼以用作Python模塊?也許這並不爲你工作..

C:\Users\niklas\Desktop>g++ -o streamtest.pyd -shared -I"C:\Python27\include" -L"C:\Python27\libs" streamtestmodule.cpp -lpython27 


C:\Users\niklas\Desktop>python 
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import streamtest 
>>> streamtest.a() 
Number set to:100 
0 

#include <Python.h> 
#include "streamtest.cpp" 

extern "C" { 

static PyObject* streamtest_a(PyObject* self) { 
    PyObject* re = Py_BuildValue("i", a()); 
    return re; 
} 

static PyMethodDef StreamtestMethods[] = { 
    {"a", (PyCFunction) streamtest_a, METH_NOARGS, NULL}, 
    {NULL, NULL, 0, NULL} 
}; 


void initstreamtest(void) { 
    PyObject* module = Py_InitModule("streamtest", StreamtestMethods); 
    if (module == NULL) { 
     cout << "Module initialization failed."; 
    } 
} 

} // extern "C" 
+0

謝謝,我也試過了python模塊版本。它給出了同樣的錯誤。我也嘗試了不同的python解釋器和g ++版本,但都給出了相同的錯誤。我也嘗試了不同的OSX版本(10.7與10.6),我沒有在10.7中得到錯誤。 – SiggyF 2012-02-29 19:58:22

+1

顯然它是一個OSX g ++ - 4.2錯誤。這是[由蘋果確認](https://discussions.apple.com/thread/2214707?start=0&tstart=0),但沒有簡單的方法,除了刪除手動定義GLIBCXXDEBUG。我設法通過編譯使用* llvm-g ++ * for OSX 10.6來解決它。將來我會嘗試使用macports的最新g ++編譯所有東西(包括python)。 – SiggyF 2012-02-29 21:11:56

相關問題