应用场景:
使用C语言实现的驱动及系统代码,需要调用C++实现的功能,就需要使用C语言来封装一下C++的接口;
本文给出了一种方法。基本思想是,写一个 wrapper文件,把 C++类封装起来,对外只提供C语言的接口,和 C++相关的都在 wrapper的实现文件里实现。
(1)C++实现一个单例,主要是通过外部设置错误码后,打印错误信息;
//Singleton.h
#include<string>
#include<map>
#include<iostream>
using namespace std;
class Singleton
{
public:
~Singleton();
Singleton(const Singleton&)=delete;
Singleton& operator=(const Singleton&)=delete;
static Singleton* get_instance();
private:
Singleton();
public:
void SetErrorCode(char* code);
void SetErrorCode(char* code, char* filename, int line);
private:
map<string, string> mapErrorCode;
};
#endif
//Singleton.cpp
#include "//Singleton.h"
Singleton::~Singleton()
{
}
Singleton* Singleton::get_instance()
{
static Singletoninstance;
return &instance;
}
Singleton::Singleton()
{
initErrorCode();
}
void Singleton::initErrorCode()
{
mapErrorCode.insert(pair<string, string>("00000","没有错误"));
}
void Singleton::SetErrorCode(char* code)
{
map<string, string>::iterator iter;
iter = mapErrorCode.find(code);
if(iter != mapErrorCode.end())
{
printf("error code is %s,detail %s\n", code, iter->second.c_str());
}
else
{
printf("error code is %s, but code is not registered\n");
}
}
void Singleton::SetErrorCode(char* code, char* filename, int line)
{
map<string, string>::iterator iter;
iter = mapErrorCode.find(code);
if(iter != mapErrorCode.end())
{
printf("error code is %s,detailed %s %s, %d\n", code, iter->second, filename, line);
}
else
{
printf("error code is %s, but code is not registered %s, %d\n", filename,line);
}
}
(2)使用Cerror_code_wrapper.h来封装C++的单例,向C语言提供接口;
//Cerror_code_wrapper.h
#ifndef _ERROR_CODE_WRAPPER_H__
#define _ERROR_CODE_WRAPPER_H__
//#include "//Singleton.h" //这里不需要加载头文件
#ifdef __cplusplus
extern "C" {
#endif
extern void SetErrorCode(char* code);
extern void SetError_detail(char* code, char* filename, int line);
#ifdef __cplusplus
};
#endif
#endif
//Cerror_code_wrapper.cpp
#include "Cerror_code_wrapper.h"
#include "Cerror_code.h"
#ifdef __cplusplus
extern "C" {
#endif
void SetErrorCode(char* code)
{
Singleton_Error::get_instance()->SetErrorCode(code);
}
void SetError_detail(char* code, char* filename, int line)
{
Singleton_Error::get_instance()->SetErrorCode(code, filename, line);
}
#ifdef __cplusplus
};
#endif
(3)测试代码实现,主函数编译使用gcc形式;
//-----test.c
#include "Cerror_code_wrapper.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
int main(void)
{
SetErrorCode("00000");
return 0;
}
g++ -c Singleton.cpp Cerror_code_wrapper.cpp
gcc test.c -o test Cerror_code_wrapper.o Singleton.o -lstdc++
参考:
https://blog.csdn.net/qq_16093323/article/details/85246650