测试实例:python继承C++接口

本文介绍了如何在Python中继承C++接口。通过创建一个工程,包含`helloworld.cpp`、`helloworld.py`和`CMakeLists.txt`,利用Boost.Python库实现了Python调用C++的接口。在`helloworld.cpp`中定义了基类`Base`和包装类`BaseWrap`,在`CMakeLists.txt`中设置了编译规则,特别针对MSVC和UNIX系统配置了不同的链接库路径。

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

新建工程文件夹,包含三个文件helloworld.cpp、helloworld.py与CMakeLists.txt

在helloworld.cpp中编写:

// 因为采用静态编译boost库,因此必须定义此宏,否则编译出错
#define BOOST_PYTHON_STATIC_LIB

#include<boost/python.hpp>
#include<boost/python/wrapper.hpp>
#include<string>
#include<iostream>

using namespace boost::python;
using namespace std;

struct Base
{
    virtual ~Base() {}
    virtual int f() { return 0; };
};

struct BaseWrap : Base, wrapper<Base>
{
    int f()
    {
        if (override f = this->get_override("f"))
            return f(); //如果函数进行重载了,则返回重载
        return Base::f(); //否则返回基类
    }
    int default_f() { return this->Base::f(); }
};

BOOST_PYTHON_MODULE(hello)
{
    class_<BaseWrap, boost::noncopyable>("Base")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值