C++ IMPL 封装 (包括python接口)

api_test.h

/*
 * @Description:
 * @Author: sk-w
 * @version:
 * @Date: 2024-08-15 14:39:03
 * @LastEditors: sk-w
 * @LastEditTime: 2024-08-26 17:21:30
 */
#pragma once
#include <memory>
#include <string>
#include <vector>

class APITest
{

public:
    int add(int a, int b);                       // 添加

    APITest();
    ~APITest();

private:
    struct Impl;
    std::unique_ptr<Impl> m_impl;
};

api_test.cpp

/*
 * @Description: 
 * @Author: sk-w
 * @version: 
 * @Date: 2024-08-15 14:39:12
 * @LastEditors: sk-w
 * @LastEditTime: 2024-08-26 17:22:56
 */
#include "api_test.h"
#include "impl_test.h"

APITest::APITest():m_impl(std::make_unique<Impl>()){};
APITest::~APITest()=default;

int APITest::add(int a, int b)
{
    return m_impl->add(a, b);
}

impl_test.h

/*
 * @Description: 
 * @Author: sk-w
 * @version: 
 * @Date: 2024-08-26 16:55:25
 * @LastEditors: sk-w
 * @LastEditTime: 2024-08-26 17:22:36
 */

# pragma once

#include "api_test.h"

struct APITest::Impl
{
    int add(int a, int b);
};




impl_test.cpp

/*
 * @Description:    
 * @Author: sk-w
 * @version: 
 * @Date: 2024-08-26 17:00:00
 * @LastEditors: sk-w
 * @LastEditTime: 2024-08-26 17:22:50
 */

#include "impl_test.h"


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

main.cpp

#include "api_test.h"
#include <iostream>


// python 封装接口,需要使用extern "C" 和__declspec(dllexport)
#define EXPORTFUC extern "C" __declspec(dllexport)

extern "C" {
    APITest* obj = new APITest();

    EXPORTFUC int add(int a, int b) {
        return obj->add(a, b);
    } // add

}


int main()
{
    APITest* api = new APITest();
    int c = api->add(1, 2);
    std::cout << c << std::endl;
}

部分参考:

C++接口文件小技巧之PIMPL详解_C 语言_脚本之家

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值