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;
}
部分参考: