例子
1. apple.h 原C++代码
#ifndef __APPLE_H__
#define __APPLE_H__
class Apple
{
public:
Apple();
int GetColor(void);
void SetColor(int color);
private:
int m_nColor;
};
#endif
2.apple.cpp 原C++代码
#include "apple.h"
Apple::Apple() : m_nColor(0)
{
}
void Apple::SetColor(int color)
{
m_nColor = color;
}
int Apple::GetColor(void)
{
return m_nColor;
}
3. AppleWrapper.h 封装文件
#ifndef _APPLE_WRAPPER_H__
#define _APPLE_WRAPPER_H_
#ifdef __cplusplus
extern "C" {
#endif
struct tagApple; // Warning: 不能使用 extern 修饰
extern struct tagApple *GetInstance(void);
extern void ReleaseInstance(struct tagApple **ppInstance);
extern void SetColor(struct tagApple *pApple, int color);
extern int GetColor(struct tagApple *pApple);
#ifdef __cplusplus
};
#endif
#endif
4.AppleWrapper.cpp 封装文件
#include "AppleWrapper.h"
#include "apple.h"
#ifdef __cplusplus
extern "C" {
#endif
struct tagApple
{
Apple apple;
};
struct tagApple *GetInstance(void)
{
return new struct tagApple;
}
void ReleaseInstance(struct tagApple **ppInstance)
{
delete *ppInstance;
*ppInstance = 0;
}
void SetColor(struct tagApple *pApple, int color)
{
pApple->apple.SetColor(color);
}
int GetColor(struct tagApple *pApple)
{
return pApple->apple.GetColor();
}
#ifdef __cplusplus
};
#endif
5.test.c 测试代码
#include "AppleWrapper.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
int main(void)
{
struct tagApple * pApple;
pApple = GetInstance();
SetColor(pApple, 1);
printf("color = %d\n", GetColor(pApple));
ReleaseInstance(&pApple);
assert(pApple == 0);
return 0;
}
参考资料:
C调用C++(C++封装以及C对其调用) - lsgxeva - 博客园