我试过链接:Calling C/C++ from python? ,但我不能这样做,这里我有声明外部“C”的问题。所以请建议假设我有一个名为“function.cpp”的函数,我必须在 python 代码中调用这个函数。 function.cpp 是:
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
然后我如何在 python 中调用这个函数,因为我是 c++ 的新手。我听说过“cython”,但我对此一无所知。
由于您使用 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
>>>