有时C程序里需要用到C++的类,但是C语言又不能直接调用类,这时需要把C++的类使用C接口封装后,再调用,
可以将封装后的C++代码编译成库文件,供C语言调用;
需要注意的是,封装的C++代码库文件是用g++编译的,所以在C中调用时,需要添加extern "C"{}关键字。
编译c代码时,要加上-lstdc++
如下代码,是c代码使用C++的map容器的例子:main函数,调用封装的C++接口:
如下代码,是c代码使用C++的map容器的例子:
//test.cpp 封装C++代码
#include <map>
#include <iostream>
#include "test.h"
using namespace std;
static map<int, int> m_testMap;
void pushVal(int key, int val)
{
m_testMap[key] = val;
}
int getVal(int key)
{
map<int, int>::iterator iter = m_testMap.find(key);
if (iter != m_testMap.end() )
{
return iter->second;
}
return -1;
}
//头文件 test.h
#ifndef _TEST_H_
#define _TEST_H_
#ifdef __cplusplus
extern "C" {
#endif
void pushVal(int key, int val);
int getVal(int key );
#ifdef __cplusplus
}
#endif
#endif
main函数调用:

编译的时候,为了简单,我这里没有编译成库文件,直接用引用.o编译的:
makefile:

编译运行结果如下:

这样在c代码里就可以使用map模板了,如果想使用实例化多个map,需要在封装代码里返回一个句柄,代表是哪个map实例;




