2012-02-29 4 views
2

문자열을 사용하여 정수를 설정하는 다음과 같은 C++ 함수가 있습니다.파이썬 ctypes를 사용하여이 extern "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에서이 함수를 어떻게 작동시킬 수 있습니까?

+0

는 파이썬 라이브러리 로더가 제대로 표준 라이브러리의 스트림에 필요한 약간의 정적/글로벌 생성자를 호출되지 않도록 될 수 있을까? –

+0

당신은 하나의 스테핑을 시도하고 그들이 어디에서 벗어나기 시작했는지 비교해 보았습니까? – PlasmaHH

+1

strm에 오류 기능이 있습니까? (하나는 strm.fail() 후 오류를 인쇄) – KevinDTimm

답변

1

x86 빌드를 사용하여 Windows 7 (x64)에서 작동합니다. 파이썬에서 모듈로 사용하기 위해 C로 코드를 래핑 해 보았습니까? 어쩌면이 .. 당신을 위해 작동 하는가

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 모듈 버전을 사용해 보았습니다. 동일한 오류가 발생합니다. 다른 파이썬 인터프리터와 g ++ 버전을 시도했지만 모두 동일한 오류가 발생합니다. 나는 또한 다른 OSX 버전 (10.7 대 10.6)을 시도했지만, 10.7에서는 오류가 발생하지 않았다. – SiggyF

+1

분명히 OSX g ++ - 4.2 버그입니다. 그것은 Apple에 의해 확인되었지만 (https://discussions.apple.com/thread/2214707?start=0&tstart=0), GLIBCXXDEBUG를 수동으로 제거하는 것 외에는 쉬운 방법이 없습니다. 필자는 * llvm-g ++ *를 사용하여 OSX 10.6을 컴파일하여 해결할 수있었습니다. 앞으로 필자는 macports의 최신 g ++를 사용하여 모든 것을 컴파일하려고 노력할 것입니다 (파이썬 포함). – SiggyF

관련 문제