在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++头文件:
- 创建Objective-C后缀文件(
.mm,如SDIOMRBridge.mm),在其中导入SDIOMR.hpp并编写OC封装接口,将C逻辑包装成OC可调用的方法。 - 新建
SDIOMRBridge.h头文件,声明需要暴露给OC代码的接口,仅在桥接头文件中导入这个OC头文件。
- 创建Objective-C后缀文件(
- 确保C++相关源文件编译模式正确:所有包含C代码的源文件都使用
.mm后缀,让编译器以Objective-C模式编译。
内容的提问来源于stack exchange,提问作者suat korkmaz
相关产品推荐
相关产品推荐

