gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:53:42 26 4
gpt4 key购买 nike

我正在尝试从 Python 脚本调用 C++ 函数。从 2010 年到 2015 年,我在 Stackoverflow 上看到了不同的解决方案,但它们都使用复杂的包,并希望有更简单/更新和更复杂的东西。我试图调用的 C++ 函数接受一个双变量并返回一个双变量。

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

最佳答案

Python 有 ctypes 包,它允许调用 DLL 或共享库中的函数。将 C++ 项目编译到 Linux 上的共享库 (.so) 或 Windows 上的 DLL 中。导出您希望对外公开的功能。
C++ 支持函数重载,为了避免二进制代码中的歧义,在函数名称中添加了附加信息,称为 name mangling 。而在 C 中,函数名称保持不变,为确保名称未更改,只需将其放置在 extern “C” 块中即可。

演示:
在这个虚拟演示中,我们的库有一个函数,获取一个 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);
}
}
我们将首先将其编译为共享对象
g++ -fPIC -shared -o libTest.so lib.cpp

现在我们将使用 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)

对于我们的测试,我们将使用 num = 16 调用该函数
test.py
from myLib import *

My_Function(16)

预期的出来也是如此。
enter image description here

关于python - Modern/2020 从 Python 调用 C++ 代码的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64084033/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com