Python中调用c/c++函数

本文介绍如何在Python中调用C/C++函数,通过实例演示了Python与C/C++混合编程的方法。详细解释了如何定义C/C++类和函数,封装C接口,并在Python中使用ctypes模块调用这些函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python中调用c/c++函数.
Python的编码速度无疑要高于C++,但有些时候,我们不得不使用C++的某些库,这个时候,可以使用Python调用c/c++的功能来实现.
C/C++部分
首先定义一个类

class Foo{
public:
    double x = 0;
public:
    double bar(double t){
        x = t;
        std::cout << "c++ " << x << std::endl;
        return x;
    }
};
// 封装C接口
extern "C"{
// 创建对象
Cbacken* cbacken_new(){
    return new Cbacken;
}
void cbacken_sort(Cbacken* cb, int *arr, int n){
    cb->sort(arr, n);
}
Foo* Foo_new(){ return new Foo(); }
double Foo_bar(Foo* cb, double t){
    double m = t;
    cb->bar(m);
    std::cout << "c " << m << "\n";
    return m;
    //return foo->bar();
    }
}

python 部分

class Foo(object):
    def __init__(self):
        self.obj = lib.Foo_new()

    def bar(self):
        lib.Foo_bar.argtypes = [ctypes.c_double]
        lib.Foo_bar.restype = ctypes.c_double
        print("python: ", lib.Foo_bar(ctypes.c_double(10.1)))

if __name__ == '__main__':
    f = Foo()
    f.bar()

值得注意的点:

  1. lib.Foo_bar.argtypes = [ctypes.c_double]
    lib.Foo_bar.restype = ctypes.c_double
    指定返回值时,主要使用的是restype.指定参数时,Foo* cb, 不需要算在内,直接制定第二个即可.
  2. 在python中调用时,并不需要对类对象进行self.obj的指定lib.Foo_bar(ctypes.c_double(10.1))).
    C++中的编译:
    set (CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/…/)
    add_library(test_lib SHARED test.cpp)

参考资料:

  1. https://stackoverflow.com/questions/22391229/ctypes-returns-wrong-result
  2. https://docs.python.org/3/library/ctypes.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

手持电烙铁的侠客

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值