2014-05-18 33 views
2

我嘗試了鏈接:Calling C/C++ from python?,但我無法做到這一點,在這裏我有extern「C」.so請求建議假設我有函數稱爲'function.cpp',我必須在python代碼中調用這個函數。 function.cpp是:如何從Python中調用類的C++函數

int max(int num1, int num2) 
{ 
    // local variable declaration 
    int result; 

    if (num1 > num2) 
    result = num1; 
    else 
    result = num2; 

    return result; 
} 

那又怎麼可以調用蟒蛇這個功能,因爲我是新的C++。我聽說過'cython',但我不知道它。

+0

檢查[boost python庫](http://www.boost.org/doc/libs/1_55_0/libs/python/doc/v2/reference.html) –

+0

只需使用python ['max()'](https: //docs.python.org/2/library/functions.html#max) – clcto

+0

@clcto其實我有另一個ADC的大代碼是在c + +,但我使用python進行編碼,所以我必須調用C++代碼在python中。上面的C++函數只是個例子 – lkkkk

回答

4

由於您使用C++,禁用名稱使用extern "C"重整(或max將被導出到像_Z3maxii一些奇怪的名稱):

#ifdef __cplusplus 
extern "C" 
#endif 
int max(int num1, int num2) 
{ 
    // local variable declaration 
    int result; 

    if (num1 > num2) 
    result = num1; 
    else 
    result = num2; 

    return result; 
} 

編譯成一些DLL或共享對象:

g++ -Wall test.cpp -shared -o test.dll # or -o test.so 

現在您可以使用ctypes

>>> from ctypes import * 
>>> 
>>> cmax = cdll.LoadLibrary('./test.dll').max 
>>> cmax.argtypes = [c_int, c_int] # arguments types 
>>> cmax.restype = c_int   # return type, or None if void 
>>> 
>>> cmax(4, 7) 
7 
>>> 
+0

你可以告訴,如果我在C++中有類,並且我必須在python中調用它,會發生什麼變化 – lkkkk

+0

@Latik不能像ctypes一樣使用C++類而不創建類似C的包裝器在[這裏](http://stackoverflow.com/questions/18590465/calling-complicated-c-functions-in-python-linux/18591226#18591226)。您也可以選擇使用SWIG,這使得將C++類包裝到Python類,[SWIG基礎知識](http://www.swig.org/Doc3.0/SWIG.html#SWIG),[SWIG和蟒](http://www.swig.org/Doc3.0/Python.html#Python)。 –

+0

thnx尋求幫助,上面給出的解決方案在Ubuntu上工作,但它不適用於Raspberry Pi,因爲它具有Raspbian操作系統。它給錯誤作爲'AttributeError:./test.dll:undefined symbol:max'請給任何解決方案。 – lkkkk