《人生苦短,我用python·十二》python通过ctype方式调用C++接口

步骤
1、编写 C++ 代码并生成共享库
2、在 Python 中使用 ctypes 调用共享库中的函数

1. 编写 C++ 代码并生成共享库
首先,我们编写一个简单的 C++ 代码并生成一个共享库(如 .dll, .so, 或 .dylib)。

C++ 代码 (example.cpp)

// example.cpp
#include <iostream>

extern "C" {
    void say_hello() {
        std::cout << "Hello from C++!" << std::endl;
    }

    int add(int a, int b) {
        return a + b;
    }

    struct Point {
        int x;
        int y;
    };

    Point create_point(int x, int y) {
        Point p;
        p.x = x;
        p.y = y;
        return p;
    }
}

编译生成共享库
在 Linux/Mac 上:

g++ -shared -o libexample.so -fPIC example.cpp

在 Windows 上:

g++ -shared -o example.dll example.cpp

2. 在 Python 中使用 ctypes 调用共享库中的函数
Python 代码

import ctypes
import os

# 加载共享库
if os.name == "nt":
    example_lib = ctypes.CDLL("./example.dll")
else:
    example_lib = ctypes.CDLL("./libexample.so")

# 调用无参数无返回值的函数
example_lib.say_hello()

# 调用有参数和返回值的函数
example_lib.add.argtypes = (ctypes.c_int, ctypes.c_int)
example_lib.add.restype = ctypes.c_int
result = example_lib.add(5, 3)
print(f"5 + 3 = {result}")

# 定义与 C++ 中结构体相同的结构体
class Point(ctypes.Structure):
    _fields_ = [("x", ctypes.c_int), ("y", ctypes.c_int)]

# 调用返回结构体的函数
example_lib.create_point.argtypes = (ctypes.c_int, ctypes.c_int)
example_lib.create_point.restype = Point
p = example_lib.create_point(10, 20)
print(f"Point: ({p.x}, {p.y})")

详细解释
1、加载共享库:

使用 ctypes.CDLL 加载共享库。路径可以是相对路径或绝对路径。

2、调用无参数无返回值的函数:

直接调用函数,无需额外设置参数或返回值类型。

3、调用有参数和返回值的函数:

使用 argtypes 指定参数类型列表。
使用 restype 指定返回值类型。
然后调用函数并处理返回值。

4、调用返回结构体的函数:

定义与 C++ 中结构体相同的 Python 结构体。
使用 argtypes 指定函数参数类型。
使用 restype 指定返回结构体类型。
调用函数并处理返回的结构体。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦回阑珊

一毛不嫌多,一分也是爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值