python - 如何从 Python 调用类的 C++ 函数

标签 python c++ function word-wrap

<分区>

我试过链接: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
>>> 

关于python - 如何从 Python 调用类的 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23724417/

相关文章:

python - 在 Django 中解压缩 Zip 文件

python - `if x:` 完全等同于 `if bool(x) is True:` 吗?

javascript - 如何在javascript中反转字符串?

c++ - C/C++ 后递增/递减和函数调用

function - 这个函数发生了什么?

python - 为什么我的学位争论表现得很奇怪?

python - 如何在 Bottle 404处理程序上传递自定义HTML?

c++ - 如何将 llvm::MemoryBuffer 的内容作为 std::string 获取?

C++ 无限符号

c++ - 从键码中获取键名(X11 XGrabKey)