# CppProjectDemo **Repository Path**: pansi18/cpp-project-demo ## Basic Information - **Project Name**: CppProjectDemo - **Description**: modern cpp project demo - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-03-21 - **Last Updated**: 2026-03-22 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # C++ CMake 项目示例 - 多算法版本管理 ## 项目概述 本项目是一个展示现代 C++ 库设计和封装的示例项目,采用了以下核心设计模式: - **C 接口封装**:将 C++ 库封装为纯 C 接口 - **策略模式**:支持多种算法版本的灵活切换 - **工厂模式**:通过注册机制实现算法的自动管理 - **公共模块**:统一管理日志、计时器、缓冲区等公共功能 - **算子库**:支持跨平台的图像算子(PC 仿真 / DSP 生产) ## 项目结构 ``` cpp-cmake-project/ ├── CMakeLists.txt # 根 CMake 配置 ├── README.md # 项目文档 ├── src/ │ ├── common/ # 公共模块 │ │ ├── CMakeLists.txt │ │ ├── include/ │ │ │ └── common.h # 公共头文件 │ │ │ ├── 日志系统(支持终端+文件输出) │ │ │ ├── 时间统计(Timer) │ │ │ └── 缓冲区管理(AlgoBuffer) │ │ └── src/ │ │ └── common.cpp │ │ │ ├── algo/ # 算法库(内部 C++ 实现) │ │ ├── CMakeLists.txt │ │ ├── include/ │ │ │ └── algo_internal.h # 算法内部接口 │ │ │ ├── IAlgoStrategy(策略接口) │ │ │ ├── AlgoStrategyFactory(工厂) │ │ │ ├── REGISTER_ALGO(注册宏) │ │ │ └── AlgoProcessor(算法处理器) │ │ └── src/ │ │ └── algo.cpp # 算法实现 + V1/V2/V3 │ │ │ ├── operator/ # 算子库(跨平台图像算子) │ │ ├── CMakeLists.txt │ │ ├── include/ │ │ │ ├── operator.h # 公共 C 接口 │ │ │ └── internal/ │ │ │ ├── scale_internal.h │ │ │ └── warp_internal.h │ │ └── src/ │ │ ├── operator_factory.cpp # 工厂实现 │ │ ├── scale/ │ │ │ ├── scale_base.cpp # ScaleBase + OpenCV/DSP 实现 │ │ │ ├── scale_opencv.cpp # OpenCV 实现(占位) │ │ │ └── scale_dsp.cpp # DSP 实现(占位) │ │ └── warp/ │ │ ├── warp_base.cpp # WarpBase + OpenCV/DSP 实现 │ │ ├── warp_opencv.cpp # OpenCV 实现(占位) │ │ └── warp_dsp.cpp # DSP 实现(占位) │ │ │ ├── proxy/ # 代理库(对外 C 接口) │ │ ├── CMakeLists.txt │ │ ├── include/ │ │ │ └── proxy.h # C 接口头文件 │ │ │ ├── ProxyParams(参数结构体) │ │ │ └── C 接口函数声明 │ │ └── src/ │ │ └── proxy.cpp # 实现 │ │ │ └── test/ # 测试程序 │ ├── CMakeLists.txt │ └── main.cpp # Demo 演示 │ └── build/ # 构建目录 └── src/test/ ├── demo.exe # 编译产物 └── log.txt # 日志文件 ``` ## 调用关系 ``` ┌─────────────────────────────────────────────────────────────┐ │ test (demo) │ │ 只调用 proxy 的 C 接口 │ └─────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ proxy (代理库,对外 C 接口) │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ ProxyParams 结构体(直接访问成员变量) │ │ │ │ - server_addr, port │ │ │ │ - algo_timeout, algo_threshold, algo_version │ │ │ └──────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ 调用 AlgoProcessor │ │ │ │ (通过工厂获取具体算法策略) │ │ │ └──────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌──────────────────────────────────────────────────────┐ │ │ │ 调用 OperatorFactory │ │ │ │ (自动检测平台,选择 OpenCV 或 DSP 实现) │ │ │ └──────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ │ ┌────────────────┼────────────────┐ ▼ ▼ ▼ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │ algo │ │ operator │ │ common │ │ (算法库) │ │ (算子库) │ │ (公共模块) │ └──────────────────┘ └──────────────────┘ └──────────────────┘ ``` ## 快速开始 ### 构建项目 ```bash # 进入项目目录 cd cpp-cmake-project # 创建构建目录 mkdir build && cd build # 配置 CMake(使用 MinGW) cmake -G "MinGW Makefiles" .. # 编译 mingw32-make # 运行 demo cd src/test ./demo.exe ``` ### 平台切换编译 ```bash # PC 仿真环境(使用 OpenCV) cmake -G "MinGW Makefiles" -DUSE_PLATFORM_OPENVINO=ON .. # DSP 生产环境 cmake -G "MinGW Makefiles" -DUSE_PLATFORM_DSP=ON .. ``` ### 查看日志 ```bash # 日志同时输出到终端和文件 cat log.txt ``` ## 核心设计详解 ### 1. C 接口封装 proxy 库对外提供纯 C 接口,便于其他语言调用: ```c // proxy.h - C 接口定义 typedef struct { char server_addr[256]; int port; int connection_timeout; int read_timeout; int max_connections; int algo_timeout; float algo_threshold; int algo_version; // 算法版本选择 } ProxyParams; typedef void* ProxyHandle; // 句柄隐藏实现 // C 接口函数 ProxyHandle proxy_init(ProxyParams* params); int proxy_connect(ProxyHandle handle); int proxy_process_with_algo(ProxyHandle handle, const char* input, char* output, int output_size); void proxy_destroy(ProxyHandle handle); ``` 使用 `extern "C"` 防止 C++ 名字修饰: ```cpp extern "C" { ProxyHandle proxy_init(ProxyParams* params) { // 实现... } } ``` ### 2. 策略模式实现多算法版本 #### 2.1 策略接口定义 ```cpp // algo_internal.h class IAlgoStrategy { public: virtual ~IAlgoStrategy() = default; // 处理算法逻辑 virtual int process(const std::string& input, std::string& output) = 0; // 获取策略名称 virtual const char* getName() const = 0; // 获取版本号 virtual AlgoVersion getVersion() const = 0; }; ``` #### 2.2 策略版本定义 ```cpp // 算法版本枚举 enum class AlgoVersion { V1 = 1, V2 = 2, V3 = 3 }; ``` #### 2.3 具体策略实现 **AlgoV1 - 简单处理:** ```cpp class AlgoV1 : public IAlgoStrategy { public: int process(const std::string& input, std::string& output) override { LOGD("ALGO_V1", "Processing with simple algorithm V1"); AlgoBuffer* buf = buffer_create(512); const char* prefix = "[V1_PROCESSED]"; buffer_append(buf, prefix, strlen(prefix)); buffer_append(buf, input.c_str(), input.length()); output = std::string((char*)buf->ptr, buf->size); buffer_destroy(buf); LOGI("ALGO_V1", "Result: %s", output.c_str()); return 0; } const char* getName() const override { return "AlgoV1"; } AlgoVersion getVersion() const override { return AlgoVersion::V1; } }; ``` **AlgoV2 - 带验证:** ```cpp class AlgoV2 : public IAlgoStrategy { public: int process(const std::string& input, std::string& output) override { LOGD("ALGO_V2", "Processing with validated algorithm V2"); // V2 新增:输入验证 if (input.empty()) { LOGW("ALGO_V2", "Input is empty, returning default"); output = "[V2_EMPTY_INPUT]"; return 0; } AlgoBuffer* buf = buffer_create(512); const char* prefix = "[V2_VALIDATED]"; buffer_append(buf, prefix, strlen(prefix)); buffer_append(buf, input.c_str(), input.length()); output = std::string((char*)buf->ptr, buf->size); buffer_destroy(buf); LOGI("ALGO_V2", "Result: %s (length: %zu)", output.c_str(), output.length()); return 0; } const char* getName() const override { return "AlgoV2"; } AlgoVersion getVersion() const override { return AlgoVersion::V2; } }; ``` **AlgoV3 - 优化处理:** ```cpp class AlgoV3 : public IAlgoStrategy { public: int process(const std::string& input, std::string& output) override { LOGD("ALGO_V3", "Processing with optimized algorithm V3"); AlgoBuffer* buf = buffer_create(512); const char* prefix = "[V3_OPTIMIZED]"; buffer_append(buf, prefix, strlen(prefix)); buffer_append(buf, input.c_str(), input.length()); // V3 新增:优化后缀 output = std::string((char*)buf->ptr, buf->size); output += "_ENHANCED"; buffer_destroy(buf); LOGI("ALGO_V3", "Result: %s (optimized)", output.c_str()); return 0; } const char* getName() const override { return "AlgoV3"; } AlgoVersion getVersion() const override { return AlgoVersion::V3; } }; ``` ### 3. 工厂模式 + 自动注册机制 #### 3.1 注册宏定义 ```cpp #define REGISTER_ALGO(version, className) \ static class className##Registrar { \ public: \ className##Registrar() { \ AlgoStrategyFactory::instance().registerStrategy( \ version, new className()); \ } \ } className##_registrar_; ``` **工作原理:** 1. `REGISTER_ALGO(AlgoVersion::V1, AlgoV1)` 展开为: ```cpp static class AlgoV1Registrar { public: AlgoV1Registrar() { AlgoStrategyFactory::instance().registerStrategy( AlgoVersion::V1, new AlgoV1()); } } AlgoV1_registrar_; ``` 2. `AlgoV1_registrar_` 是静态变量,程序启动时自动调用构造函数 3. 构造函数中调用 `registerStrategy()` 将算法注册到工厂 #### 3.2 工厂实现 ```cpp class AlgoStrategyFactory { public: // 单例访问点 static AlgoStrategyFactory& instance() { static AlgoStrategyFactory factory; return factory; } // 注册策略 bool registerStrategy(AlgoVersion version, IAlgoStrategy* strategy) { if (strategies_.find(version) != strategies_.end()) { LOGW("ALGO_FACTORY", "Strategy version %d already registered", (int)version); return false; } strategies_[version] = strategy; LOGI("ALGO_FACTORY", "Registered algorithm version: %d", (int)version); return true; } // 获取策略 IAlgoStrategy* getStrategy(AlgoVersion version) { auto it = strategies_.find(version); if (it != strategies_.end()) { return it->second; } LOGE("ALGO_FACTORY", "Strategy version %d not found", (int)version); return nullptr; } private: std::map strategies_; }; ``` #### 3.3 注册使用 ```cpp // algo.cpp 末尾 REGISTER_ALGO(AlgoVersion::V1, AlgoV1) REGISTER_ALGO(AlgoVersion::V2, AlgoV2) REGISTER_ALGO(AlgoVersion::V3, AlgoV3) ``` ### 4. AlgoProcessor 使用工厂 ```cpp class AlgoProcessor { public: bool init(int timeout, float threshold, AlgoVersion version) { timeout_ = timeout; threshold_ = threshold; version_ = version; // 通过工厂获取策略 strategy_ = AlgoStrategyFactory::instance().getStrategy(version_); if (!strategy_) { LOGE("ALGO", "Failed to get algorithm strategy"); return false; } initialized_ = true; LOGI("ALGO", "Initialized with %s", strategy_->getName()); return true; } int process(const std::string& input) { // 调用策略的 process 方法 return strategy_->process(input, result_); } private: AlgoVersion version_; IAlgoStrategy* strategy_; // 当前使用的策略 }; ``` ### 5. 公共日志模块 ```cpp // 日志宏(自动记录文件、行号、函数名) #define LOGI(tag, fmt, ...) \ common_log(LOG_LEVEL_INFO, tag, __FILE__, __LINE__, __FUNCTION__, fmt, ##__VA_ARGS__) // 输出格式 // [2026-03-21 16:51:41] [INFO][ALGO] [algo.cpp:153][init] Initialized with AlgoV1 // 时间 级别 标签 文件:行号 函数名 内容 ``` 日志同时输出到终端和文件: ```cpp void common_log(...) { // 输出到终端 fprintf(stdout, "[%s] [%s][%s] [%s:%d][%s] %s\n", ...); // 输出到文件 if (g_log_config.enable_file_output && g_log_file) { fprintf(g_log_file, "[%s] [%s][%s] [%s:%d][%s] %s\n", ...); fflush(g_log_file); } } ``` ## 算子库设计(Operator Library) ### 设计背景 在实际项目中,某些算子(如图像缩放、旋转、格式转换)需要在不同平台上使用不同的实现: - **仿真环境(PC)**:使用 C++/OpenCV 实现,方便调试和快速验证 - **生产环境(开发板)**:调用 DSP 硬件加速,提高性能 ### 架构设计 ``` ┌─────────────────────────────────────────────────────────────────────────┐ │ Operator Library │ │ │ │ ┌─────────────────────────────────────────────────────────────────┐ │ │ │ operator.h (公共 C 接口) │ │ │ │ - OPERATOR_TYPE_SCALE, OPERATOR_TYPE_WARP │ │ │ │ - OPERATOR_IMPL_AUTO_CV, OPERATOR_IMPL_DSP │ │ │ │ - ImageData, ScaleParams, WarpParams │ │ │ │ - operator_create(), operator_process(), operator_destroy() │ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────────────┐ │ │ │ OperatorFactory (工厂) │ │ │ │ - IOperator 接口 │ │ │ │ - ScaleOperator, WarpOperator │ │ │ │ - 根据 impl_type 创建具体实现 │ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ┌───────────────────────────┼───────────────────────────┐ │ │ ▼ ▼ ▼ │ │ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │ │ │ Scale │ │ Scale │ │ Warp │ │ │ │ OpenCV │ │ DSP │ │ OpenCV │ │ │ └───────────────┘ └───────────────┘ └───────────────┘ │ │ │ │ │ │ │ └───────────────────────────┼───────────────────────────┘ │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────────────┐ │ │ │ common (公共模块) │ │ │ │ - LOGD/LOGI/LOGW/LOGE │ │ │ └─────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────┘ ``` ### 目录结构 ``` src/operator/ ├── CMakeLists.txt ├── include/ │ ├── operator.h # 公共 C 接口 │ └── internal/ │ ├── scale_internal.h # Scale 内部接口 │ └── warp_internal.h # Warp 内部接口 └── src/ ├── operator_factory.cpp # 工厂实现 ├── scale/ │ ├── scale_base.cpp # ScaleBase + OpenCV/DSP 实现 │ ├── scale_opencv.cpp # OpenCV 实现占位 │ └── scale_dsp.cpp # DSP 实现占位 └── warp/ ├── warp_base.cpp # WarpBase + OpenCV/DSP 实现 ├── warp_opencv.cpp # OpenCV 实现占位 └── warp_dsp.cpp # DSP 实现占位 ``` ### 算子类型定义 ```c // 算子类型 #define OPERATOR_TYPE_SCALE 1 #define OPERATOR_TYPE_WARP 2 // 实现类型 #define OPERATOR_IMPL_AUTO 0 // 自动选择 #define OPERATOR_IMPL_AUTO_CV 1 // OpenCV 实现 #define OPERATOR_IMPL_DSP 2 // DSP 实现 ``` ### 数据结构 ```c // 图像数据结构 typedef struct { int src_width; int src_height; int src_stride; int dst_width; int dst_height; int dst_stride; uint8_t* src_data; uint8_t* dst_data; } ImageData; // 缩放参数 typedef struct { float scale_x; float scale_y; int interpolation; } ScaleParams; // 仿射变换参数 typedef struct { float matrix[9]; // 3x3 仿射变换矩阵 int flags; } WarpParams; ``` ### C 接口定义 ```c // 算子句柄 typedef void* OperatorHandle; // 创建算子 // operator_type: OPERATOR_TYPE_SCALE 或 OPERATOR_TYPE_WARP // impl_type: OPERATOR_IMPL_AUTO_CV 或 OPERATOR_IMPL_DSP OperatorHandle operator_create(int operator_type, int impl_type); // 处理图像 int operator_process(OperatorHandle handle, void* params, const ImageData* src, ImageData* dst); // 销毁算子 void operator_destroy(OperatorHandle handle); // 获取算子信息 const char* operator_get_name(OperatorHandle handle); const char* operator_get_impl(OperatorHandle handle); ``` ### Scale 算子实现 #### ScaleBase 抽象基类 ```cpp class ScaleBase { public: ScaleBase() : impl_(nullptr) {} virtual ~ScaleBase() {} const char* getName() const { return "Scale"; } void setImpl(IScaleImpl* impl) { impl_ = impl; } int process(const ScaleParams* params, const ImageData* src, ImageData* dst) { if (!impl_) { LOGE("SCALE", "No implementation set"); return -1; } return impl_->process(params, src, dst); } const char* getImplName() const { if (!impl_) return "UNKNOWN"; return impl_->getName(); } protected: IScaleImpl* impl_; }; ``` #### OpenCV 实现 ```cpp class ScaleOpenCV : public IScaleImpl { public: ScaleOpenCV() { LOGI("SCALE", "OpenCV scale implementation created"); } const char* getName() const override { return "OpenCV"; } int process(const ScaleParams* params, const ImageData* src, ImageData* dst) override { // 计算目标尺寸 dst->dst_width = (int)(src->src_width * params->scale_x); dst->dst_height = (int)(src->src_height * params->scale_y); // 分配目标缓冲区 dst->dst_data = (uint8_t*)malloc(dst->dst_width * dst->dst_height); // 双线性插值缩放实现 for (int dy = 0; dy < dst->dst_height; dy++) { float sy = (float)dy / dst->dst_height * src->src_height; // ... 插值计算 ... } return 0; } }; ``` #### DSP 实现 ```cpp class ScaleDSP : public IScaleImpl { public: ScaleDSP() { LOGI("SCALE", "DSP scale implementation created (production mode)"); } const char* getName() const override { return "DSP"; } int process(const ScaleParams* params, const ImageData* src, ImageData* dst) override { // 计算目标尺寸 dst->dst_width = (int)(src->src_width * params->scale_x); dst->dst_height = (int)(src->src_height * params->scale_y); // 分配目标缓冲区 dst->dst_data = (uint8_t*)malloc(dst->dst_width * dst->dst_height); // 调用 DSP 硬件加速 // dsp_scale_execute(src->src_data, dst->dst_data, ...); LOGI("SCALE", "DSP scale completed (data copied to DSP memory)"); return 0; } }; ``` ### Warp 算子实现 ```cpp class WarpBase { public: WarpBase() : impl_name_("UNKNOWN") {} virtual ~WarpBase() {} virtual const char* getName() const { return "Warp"; } virtual int process(const WarpParams* params, const ImageData* src, ImageData* dst) = 0; void setImplName(const char* name) { impl_name_ = name ? name : "UNKNOWN"; } const char* getImplName() const { return impl_name_; } protected: const char* impl_name_; }; class WarpOpenCV : public WarpBase { public: WarpOpenCV() { setImplName("OpenCV"); } int process(const WarpParams* params, const ImageData* src, ImageData* dst) override { // 应用仿射变换矩阵 for (int y = 0; y < dst->dst_height; y++) { for (int x = 0; x < dst->dst_width; x++) { float sx = params->matrix[0] * x + params->matrix[1] * y + params->matrix[2]; float sy = params->matrix[3] * x + params->matrix[4] * y + params->matrix[5]; // ... 坐标映射 ... } } return 0; } }; class WarpDSP : public WarpBase { public: WarpDSP() { setImplName("DSP"); } int process(const WarpParams* params, const ImageData* src, ImageData* dst) override { // 调用 DSP 硬件加速进行仿射变换 // dsp_warp_execute(src->src_data, dst->dst_data, params->matrix, ...); return 0; } }; ``` ### 工厂模式创建算子 ```cpp // C 接口实现 extern "C" { OperatorHandle operator_create(int operator_type, int impl_type) { IOperator* op = nullptr; switch (operator_type) { case OPERATOR_TYPE_SCALE: op = new ScaleOperator(impl_type); break; case OPERATOR_TYPE_WARP: op = new WarpOperator(impl_type); break; default: LOGE("OPERATOR", "Unknown operator type: %d", operator_type); return nullptr; } LOGI("OPERATOR", "Created operator: %s (impl: %s)", op->getName(), ((ConcreteOperator*)op)->getImplName()); return (OperatorHandle)op; } } ``` ### 平台自动检测与切换 proxy 库通过编译时宏定义实现平台自动检测: ```cpp // proxy.cpp 中定义平台检测宏 #ifdef USE_PLATFORM_DSP #define CURRENT_PLATFORM "DSP" #define AUTO_IMPL_TYPE OPERATOR_IMPL_DSP #elif defined(USE_PLATFORM_OPENVINO) #define CURRENT_PLATFORM "OpenVINO" #define AUTO_IMPL_TYPE OPERATOR_IMPL_AUTO_CV #else #if defined(PLATFORM_WINDOWS) || defined(PLATFORM_LINUX) #define CURRENT_PLATFORM "OpenCV (Simulation)" #define AUTO_IMPL_TYPE OPERATOR_IMPL_AUTO_CV #else #define CURRENT_PLATFORM "DSP (Default)" #define AUTO_IMPL_TYPE OPERATOR_IMPL_DSP #endif #endif ``` ### 编译时平台切换 ```bash # PC 仿真环境(默认) cmake -G "MinGW Makefiles" .. mingw32-make # 强制使用 DSP 实现 cmake -G "MinGW Makefiles" -DUSE_PLATFORM_DSP=ON .. mingw32-make # 强制使用 OpenCV 实现 cmake -G "MinGW Makefiles" -DUSE_PLATFORM_OPENVINO=ON .. mingw32-make ``` ### 运行时切换 ```c // 通过参数指定使用哪种实现 int operator_type = IMAGE_OPERATOR_OPENVINO; // 或 IMAGE_OPERATOR_DSP ImageOperatorHandle handle = image_operator_create(operator_type); // 缩放图像 int result = image_operator_resize(handle, src_data, 640, 480, 3, dst_data, 320, 240, 0); ``` ### 仿真与生产切换对比 | 特性 | PC 仿真 (OpenCV) | DSP 生产 | |------|------------------|----------| | 编译宏 | `USE_PLATFORM_OPENVINO` 或默认 | `USE_PLATFORM_DSP` | | 实现方式 | C++ / OpenCV 软件实现 | DSP 硬件加速 | | 调试 | 支持断点、日志详细 | 需连接硬件调试器 | | 性能 | 依赖 CPU | 硬件加速,高性能 | | 适用场景 | 开发、测试、验证 | 最终产品部署 | ## 使用示例 ### 完整 Demo ```cpp #include "proxy.h" #include "common.h" int main() { LOGI("TEST", "Testing multiple algo versions"); const char* testData = "Hello Algorithm"; // 测试三种算法版本 for (int version = 1; version <= 3; version++) { LOGI("TEST", "Testing with Algo Version %d", version); // 1. 配置参数 ProxyParams params = {}; strncpy(params.server_addr, "192.168.1.100", 255); params.port = 8080; params.algo_version = version; // 指定算法版本 // 2. 初始化 ProxyHandle handle = proxy_init(¶ms); // 3. 连接 proxy_connect(handle); // 4. 使用指定算法处理 char output[512]; proxy_process_with_algo(handle, testData, output, sizeof(output)); // 5. 清理 proxy_destroy(handle); } return 0; } ``` ### 图像算子使用示例 ```cpp // 创建图像算子(自动检测平台) ImageOperatorHandle handle = image_operator_create(IMAGE_OPERATOR_OPENVINO); // 图像数据 int src_width = 640; int src_height = 480; uint8_t* src_data = /* 图像数据 */; int dst_width = 320; int dst_height = 240; uint8_t* dst_data = (uint8_t*)malloc(dst_width * dst_height); // 图像缩放 int result = image_operator_resize(handle, src_data, src_width, src_height, 3, dst_data, dst_width, dst_height, 0); // 清理 free(src_data); free(dst_data); image_operator_destroy(handle); ``` ### 使用算子库 API ```cpp // 创建 Scale 算子(OpenCV 实现) OperatorHandle scale_op = operator_create(OPERATOR_TYPE_SCALE, OPERATOR_IMPL_AUTO_CV); // 准备图像数据 ImageData src = {}; src.src_width = 640; src.src_height = 480; src.src_stride = 640; src.src_data = /* 源图像数据 */; ImageData dst = {}; // 设置缩放参数(缩小 50%) ScaleParams params = {0.5f, 0.5f, 0}; // 执行缩放 int result = operator_process(scale_op, ¶ms, &src, &dst); // 获取实现信息 LOGI("TEST", "Using %s implementation", operator_get_impl(scale_op)); // 清理 operator_destroy(scale_op); ``` ### 运行结果 ``` [INFO][PROXY] Platform detection: OpenCV (Simulation), auto impl: OpenCV [INFO][TEST] Testing with Algo Version 1 [INFO][ALGO] Initialized with AlgoV1 [INFO][ALGO_V1] Result: [V1_PROCESSED]Hello Algorithm [INFO][TEST] Testing with Algo Version 2 [INFO][ALGO] Initialized with AlgoV2 [INFO][ALGO_V2] Result: [V2_VALIDATED]Hello Algorithm [INFO][TEST] Testing with Algo Version 3 [INFO][ALGO] Initialized with AlgoV3 [INFO][ALGO_V3] Result: [V3_OPTIMIZED]Hello Algorithm_ENHANCED [INFO][TEST] Testing Image Operators [INFO][OPERATOR] Created operator: Scale (impl: OpenCV) [DEBUG][SCALE] OpenCV scale: 640x480 -> 320x240 [INFO][SCALE] OpenCV scale completed: 640x480 -> 320x240 ``` ## 扩展新算子 ### 步骤 1:定义算子类型 ```c // operator.h #define OPERATOR_TYPE_ROTATE 3 ``` ### 步骤 2:创建算子基类 ```cpp // src/operator/src/rotate/rotate_base.cpp class RotateBase { public: virtual ~RotateBase() {} virtual const char* getName() const = 0; virtual int process(const RotateParams* params, const ImageData* src, ImageData* dst) = 0; }; class RotateOpenCV : public RotateBase { public: const char* getName() const override { return "Rotate"; } int process(const RotateParams* params, const ImageData* src, ImageData* dst) override { // OpenCV 旋转实现 } }; class RotateDSP : public RotateBase { public: const char* getName() const override { return "Rotate"; } int process(const RotateParams* params, const ImageData* src, ImageData* dst) override { // DSP 旋转实现 } }; ``` ### 步骤 3:更新工厂 ```cpp // src/operator/src/operator_factory.cpp class RotateOperator : public IOperator { public: RotateOperator(int impl_type) { impl_ = rotate_create(impl_type); } const char* getName() const override { return "Rotate"; } int process(void* params, const ImageData* src, ImageData* dst) override { return rotate_process(impl_, (const RotateParams*)params, src, dst); } private: RotateBase* impl_; }; // 在 operator_create 中添加 case OPERATOR_TYPE_ROTATE: op = new RotateOperator(impl_type); break; ``` ## 设计优势 ### 1. 策略模式优势 | 特性 | 说明 | |------|------| | **开闭原则** | 新增算子无需修改现有代码 | | **单一职责** | 每个算子独立实现自己的逻辑 | | **可替换性** | 可在运行时切换实现 | | **解耦合** | 调用方与实现分离 | ### 2. 工厂模式优势 | 特性 | 说明 | |------|------| | **自动注册** | 静态变量确保全局初始化 | | **集中管理** | 所有算子在工厂统一管理 | | **按需获取** | 调用时才创建/获取实例 | | **类型安全** | 使用枚举避免字符串硬编码 | ### 3. 跨平台切换优势 | 特性 | 说明 | |------|------| | **编译时切换** | 通过 CMake 定义切换平台 | | **运行时选择** | 通过参数选择实现版本 | | **无缝对接** | 统一 C 接口,无需修改业务代码 | | **独立实现** | OpenCV/DSP 实现完全独立 | ### 4. 避免 if-else 传统方式(需大量条件判断): ```cpp // ❌ 不推荐 if (platform == "opencv") { ScaleOpenCV op; op.process(); } else if (platform == "dsp") { ScaleDSP op; op.process(); } // ... 更多平台... ``` 工厂模式(零 if-else): ```cpp // ✅ 推荐 IOperator* op = operatorFactory.create(type); op->process(); ``` ## 依赖关系 ``` test (可执行文件) └── proxy (静态库) ├── common (静态库) ├── algo (静态库) │ └── common (静态库) └── operator (静态库) └── common (静态库) ``` ## 编译说明 ### 环境要求 - CMake >= 3.15 - C++17 支持 - MinGW / GCC / MSVC ### CMake 配置选项 ```bash # 使用 MinGW cmake -G "MinGW Makefiles" .. # 使用 MSVC cmake -G "Visual Studio 17 2022" -A x64 .. # 使用 Ninja cmake -G "Ninja" .. # 强制使用 DSP 平台 cmake -G "MinGW Makefiles" -DUSE_PLATFORM_DSP=ON .. # 强制使用 OpenCV 平台 cmake -G "MinGW Makefiles" -DUSE_PLATFORM_OPENVINO=ON .. ``` ## 日志输出 日志文件 `log.txt` 记录完整的运行过程: ``` ========== Log started at 2026-03-21 16:51:41 ========== [2026-03-21 16:51:41] [INFO][ALGO_FACTORY] [algo.cpp:108][registerStrategy] Registered algorithm version: 1 [2026-03-21 16:51:41] [INFO][ALGO_FACTORY] [algo.cpp:108][registerStrategy] Registered algorithm version: 2 [2026-03-21 16:51:41] [INFO][ALGO_FACTORY] [algo.cpp:108][registerStrategy] Registered algorithm version: 3 [2026-03-21 16:51:41] [INFO][PROXY] Platform detection: OpenCV (Simulation), auto impl: OpenCV [2026-03-21 16:51:41] [INFO][OPERATOR] Created operator: Scale (impl: OpenCV) ... ``` ## 总结 本项目展示了现代 C++ 库设计的最佳实践: 1. **C 接口封装**:使 C++ 库可以被 C、Python、Lua 等语言调用 2. **策略模式**:灵活支持多种算法实现 3. **工厂模式**:通过注册机制简化管理 4. **算子库**:支持跨平台的图像算子(PC 仿真 / DSP 生产) 5. **公共模块**:统一日志、计时器、缓冲区等功能 6. **平台切换**:编译时/运行时灵活选择实现版本 这些设计模式组合使用,使项目具有良好的**可扩展性**、**可维护性**和**可测试性**。