C调用C++(C++封装以及C对其调用)

例子

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 - 博客园

C中如何调用C++函数 - franksunny的个人技术空间 - C++博客

C代码中如何调用C++ C++中如何调用C - Yogurshine - 博客园

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值