如何从Python调用类的C ++函数 [英] How to call C++ functions of a class from a Python

查看:133
本文介绍了如何从Python调用类的C ++函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了链接:从Python调用C / C ++?,但我是无法做到这一点,在这里我有externC声明的问题。所以请建议假设我有一个名为'function.cpp'的函数,我必须在python代码中调用这个函数。 function.cpp是:

  int max(int num1,int num2)
{
// local变量声明
int结果;

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

返回结果;

然后我可以在python中调用这个函数,因为我是新的c ++ 。我听说过'cython',但我不知道它。

解决方案

由于您使用C ++,因此使用 externC(或者 max )会被导出为一些奇怪的名字,比如 _Z3maxii
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b int max(int num1,int num2)
{
//局部变量声明
int结果;

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

返回结果;
}

编译成某个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]#参数类型
>>> cmax.restype = c_int#返回类型,如果无效则返回None
>>>
>>> cmax(4,7)
7
>>>


I tried with the link: Calling C/C++ from python?, but I am not able to do the same, here I have problem of declaring extern "C".so please suggest suppose I have the function called 'function.cpp' and I have to call this function in the python code. function.cpp is:

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

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

  return result; 
 }

Then how i can call this function in python, as I am new for c++. I heard about the 'cython' but I have no idea about it.

解决方案

Since you use C++, disable name mangling using extern "C" (or max will be exported into some weird name like _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; 
}

Compile it into some DLL or shared object:

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

now you can call it using 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调用类的C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆