2014-05-18 17 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