You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Swift Xcode项目中添加C++代码时出错,请求协助解决

问题解决请求

桥接头文件内容

#import "OpenCVWrapper.h"
#import "sdi_omr/src/SDIOMR.hpp"

相关文件说明

SDIOMR.hpp已设置为默认C++头文件,对应的SDIOMR.cpp存在且设置为默认C++源文件,其代码如下:

#ifndef SDIOMR_H
#define SDIOMR_H

#ifdef __cplusplus
#include <opencv2/opencv.hpp>
#include <vector> 
#include <map>
#include "ImagePreprocessor.hpp"
#include "INIReader.hpp"
#endif

class SDIOMR{
    private:
        bool isProcessable = false;
        cv::Mat fixedFrame;
        cv::Mat inputFrame;
        ImagePreprocessor imagePreprocessor;
        std::vector<cv::Mat> segments;
        INIReader reader;
    public:
        bool isReadable(cv::Mat frame);
        std::vector<std::vector<int>> readForm();
        // SDIOMR();
        SDIOMR(INIReader inireader);
};

#endif // SDIOMR_H

编译错误

当前出现以下编译错误:

  • Unknown type name 'class'; did you mean 'Class'?
  • Unknown type name 'cv'
  • 无法识别std::vector等C++语法元素

解决方法

  • 修正头文件的C++代码包裹范围:将SDIOMR类的定义移入#ifdef __cplusplus块内部,确保非C编译环境不会解析C语法。修改后的SDIOMR.hpp代码如下:
    #ifndef SDIOMR_H
    #define SDIOMR_H
    
    #ifdef __cplusplus
    #include <opencv2/opencv.hpp>
    #include <vector> 
    #include <map>
    #include "ImagePreprocessor.hpp"
    #include "INIReader.hpp"
    
    class SDIOMR{
        private:
            bool isProcessable = false;
            cv::Mat fixedFrame;
            cv::Mat inputFrame;
            ImagePreprocessor imagePreprocessor;
            std::vector<cv::Mat> segments;
            INIReader reader;
        public:
            bool isReadable(cv::Mat frame);
            std::vector<std::vector<int>> readForm();
            // SDIOMR();
            SDIOMR(INIReader inireader);
    };
    #endif // __cplusplus
    
    #endif // SDIOMR_H
    
  • 避免在桥接头文件直接导入C++头文件:
    1. 创建Objective-C后缀文件(.mm,如SDIOMRBridge.mm),在其中导入SDIOMR.hpp并编写OC封装接口,将C逻辑包装成OC可调用的方法。
    2. 新建SDIOMRBridge.h头文件,声明需要暴露给OC代码的接口,仅在桥接头文件中导入这个OC头文件。
  • 确保C++相关源文件编译模式正确:所有包含C代码的源文件都使用.mm后缀,让编译器以Objective-C模式编译。

内容的提问来源于stack exchange,提问作者suat korkmaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 04:00:08