简体   繁体   English

Modern/2020 从 Python 调用 C++ 代码的方法

[英]Modern/2020 way to call C++ code from Python

I am trying to call a C++ function from a Python script.我正在尝试从 Python 脚本调用 C++ 函数。 I have seen different solutions on Stackoverflow from 2010-2015 but they are all using complicated packages and was hoping for something easier/newer and more sophisticated.从 2010 年到 2015 年,我在 Stackoverflow 上看到了不同的解决方案,但它们都使用复杂的包,并希望有更简单/更新和更复杂的东西。 The C++ function I am trying to call takes in a double variable and returns a double.我试图调用的 C++ 函数接受一个双变量并返回一个双变量。

double foo(double var1){
    double result = ...
    return result;
}

Python has ctypes package which allows calling functions in DLLs or shared libraries. Python 有ctypes包,它允许调用 DLL 或共享库中的函数。 Compile your C++ project into a shared library (.so) on Linux, or DLL on Windows.将 C++ 项目编译到 Linux 上的共享库 (.so) 或 Windows 上的DLL Export the functions you wish to expose outside.导出您希望对外公开的功能。

C++ supports function overloading, to avoid ambiguity in the binary code, additional information is added to function names, known as name mangling . C++ 支持函数重载,为了避免二进制代码中的歧义,在函数名中添加了额外的信息,称为name mangling Whereas, in C function names are unchanged, to ensure no name is changed, simply place inside an extern “C” block.而在 C 中,函数名称保持不变,为确保名称未更改,只需将其放置在 extern “C” 块中即可。


Demo: In this dummy demo, our library has a single function, taking an int and printing it.演示:在这个虚拟演示中,我们的库只有一个函数,获取一个 int 并打印它。

lib.cpp库文件

#include <iostream>

int Function(int num) 
{
    std::cout << "Num = " << num << std::endl;
    return 0;
}

extern "C" {
    int My_Function(int a)
    {
        return Function(a);
    }
}

We will compile this into a shared object first我们将首先将其编译为共享对象

g++ -fPIC -shared -o libTest.so lib.cpp

Now we will utilized ctypes, to load the shared object/dll and functions.现在我们将使用 ctypes 来加载共享对象/dll 和函数。

myLib.py我的库文件

import ctypes
import sys
import os 

dir_path = os.path.dirname(os.path.realpath(__file__))
handle = ctypes.CDLL(dir_path + "/libTest.so")     

handle.My_Function.argtypes = [ctypes.c_int] 
  
def My_Function(num):
    return handle.My_Function(num)    

For our test, we will call the function with num = 16对于我们的测试,我们将调用num = 16的函数

test.py测试文件

from myLib import *

My_Function(16)

The expected out as well.预期的出来也是如此。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM