程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python 语言如何和 C/C++ 语言交互使用

hfteth 2024-12-23 09:23:16 技术文章 20 ℃

Python 提供了多种方式与 C/C++ 语言进行交互使用,以下是几种常见的方法:

1. Python 使用 C/C++ 扩展库:

1.1 使用内置的 ctypes 模块:可以用于调用动态链接库(.so 文件)中的 C/C++ 函数。可以使用 ctypes 模块加载 C/C++ 编写的动态链接库,并使用 ctypes 提供的函数指针类型和函数调用方式来调用其中的函数。

// example.c

// 编译生成动态链接库
// gcc -fPIC -shared example.c -o example.so

#include <stdio.h>
#include <stdlib.h>

int add(int a, int b)
{
    return a + b;
}
# test.py

# 运行测试脚本
# python test.py

from ctypes import CDLL
example = CDLL('./example.so')

print(example.add(1, 2))

1.2 使用 Ctypesgen:Ctypesgen 是一个 Python 脚本,可以根据 C/C++ 头文件自动生成 Python 的 ctypes 代码。你只需要提供 C/C++ 头文件,然后运行 Ctypesgen 脚本,即可生成对应的 Python 模块。

// example.h

// 依据 C 语言头文件生成 Python 接口文件
// ctypesgen -a -l _example example.h -o example.py

#ifndef EXAMPLE_H
#define EXAMPLE_H

int add(int a, int b);

#endif // EXAMPLE_H
// example.c

// 生成共享库
// gcc  --share -fPIC example.c -o _example.so

int add(int a, int b)
{
    return a + b;
}
# test.py

# 运行测试脚本
# python test.py

import example

print(example.add(1, 2))

1.3 使用 SWIG(Simplified Wrapper and Interface Generator):SWIG 是一个开源工具,可以自动生成 Python 和 C/C++ 之间的接口代码。你可以使用 SWIG 编写一个接口描述文件,然后使用 SWIG 生成对应的 Python 模块,使得 Python 可以直接调用 C/C++ 函数。

// example.c

int add(int a, int b) {
    return a + b;
}
// example.i

// 依据接口描述文件生成 example_wrap.c 和 example.py 文件
// swig -python example.i
// 根据 example_wrap.c 文件生成 _example*.so 共享库
// gcc -shared -fPIC `python3-config --includes` example_wrap.c -o _example`python3-config --extension-suffix`

%module example

%{
#include "example.c"
%}

%include "example.c"
# test.py

# 运行测试脚本
# python test.py

import example

print(example.add(1, 2))

1.4 使用 Pybind11:Pybind11 是一个开源库,可以用于将 C++ 代码包装成 Python 模块。你可以使用 Pybind11 编写一个 C++ 扩展模块,然后 Python 中导入和使用该模块。

// exmpale.cpp

// 编译生成动态链接库
// g++ -std=c++11 -shared -fPIC `python -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`

#include <pybind11/pybind11.h>

namespace example
{
    int add(int i, int j)
    {
        return i + j;
    }
}

int sub(int i, int j)
{
    return i - j;
}

PYBIND11_MODULE(example, m)
{
    m.doc() = "pybind11 example plugin";
    m.def("add", &example::add, "A function that two numbers adds ");
    m.def("sub", &sub, "A function that two numbers sub");
}
# test.py

# 运行测试脚本
# python test.py

import example

print(example.add(1, 2))
print(example.sub(4, 2))

2. Python 生成 C/C++ 扩展库:

2.1 使用 Cython:Cython 是一个将 Python 代码转换为 C/C++ 扩展模块的工具。你可以使用 Cython 编写一个扩展模块,其中可以包含 C/C++ 的代码,通过 C/C++ 编译器进行编译。生成的代码经过优化,可以获得接近原生 C/C++ 代码的执行性能,并且可以直接在 Python 中导入和使用该扩展模块。

# example.py

# 编译生成动态链接库
# cythonize example.py -i

def fib(n):
    """Print the Fibonacci series up to n."""
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a + b
# test.py

# 运行测试脚本
# python test.py

import example

print(example.fib(9))

以上是一些常见的方法,你可以根据具体的需求选择合适的方法与 C/C++ 语言进行交互使用。

Tags:

最近发表
标签列表