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 语言_脚本之家

### Python 中集成和使用 C++ 代码 #### 方法一:通过 Python/C API 实现 Python/C API 提供了一种机制,使得可以在 C++ 程序中嵌入 Python 解释器并调用 Python 函数。这种方式虽然较为底层,但是提供了极大的灵活性和控制力[^1]。 ```cpp // example.cpp #include <Python.h> int main(int argc, char *argv[]) { Py_Initialize(); PyObject* pyResult; const char* pythonCode = "print('Hello from Python')"; pyResult = PyRun_String(pythonCode, Py_eval_input, NULL, NULL); if (pyResult != NULL) { Py_DECREF(pyResult); } else { PyErr_Print(); } Py_Finalize(); } ``` 此段代码展示了如何初始化 Python 解释器,在 C++ 环境下执行简单的 Python 命令,并最终释放资源。 #### 方法二:创建 Python 扩展模块 另一种常见的方式是编写可以被 Python 导入的扩展模块。这通常涉及到定义接口函数并将它们编译成共享库文件(如 `.so` 或者 `.dll`),之后就可以像导入常规 Python 模块一样来加载这些自定义构建的组件[^2]。 ```cpp // demo_module.cpp #define PY_SSIZE_T_CLEAN #include <Python.h> static PyObject* hello_world(PyObject* self, PyObject* args){ printf("Hello world!\n"); Py_RETURN_NONE; } static PyMethodDef DemoMethods[] = { {"hello", hello_world, METH_NOARGS, "Prints Hello World."}, {NULL, NULL, 0, NULL} /* Sentinel */ }; static struct PyModuleDef demomodule = { PyModuleDef_HEAD_INIT, "demo", NULL, -1, DemoMethods }; PyMODINIT_FUNC PyInit_demo(void) { return PyModule_Create(&demomodule); } ``` 这段代码展示了一个基本的例子,其中 `hello_world()` 成为了可由 Python 访问的功能之一。 #### 方法三:利用 ctypes 加载动态链接库 对于那些已经存在并且不需要修改源码就能工作的现有 C++ 库来说,ctypes 可能是最简单快捷的选择。只需要按照标准流程编译好目标平台上的 .dll 或.so 文件即可。 ```python from ctypes import cdll lib = cdll.LoadLibrary('./example.dll') # Windows 下路径可能不同 result = lib.some_function() print(f"The result is {result}") ``` 这里假设有一个名为 `some_function` 的外部 C++ 函数存在于指定位置的 DLL/SO 文件里。 #### 类映射实例 当希望更紧密地结合两者时,则可以通过特定工具或框架完成更加复杂的操作,比如将 C++ 类成员函数映射至 Python 对象属性/方法上[^3]: ```cpp class CplusplusClass { public: int getValue() const{return value;} void setValue(int v){value=v;} private: int value{42}; }; ``` 对应的 Python 封装可能是这样的形式: ```python class DemoClass(object): def __init__(self): self._impl = ... # 这里应该是实际连接到C++对象的地方 def getValue(self): return self._impl.getValue() def setValue(self, val): self._impl.setValue(val) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值