从C调用C ++类方法

如果要从C内部从C ++调用类方法,请使用类包装器。

这种方法的一个优点是C ++类保持不变,并且可以

甚至存在于图书馆中

首先,让我们定义C ++类“ Circle”。 为了简单起见,我们会做的一切

在.h文件中,但对于在.h中声明并定义的类也同样有效

在.cpp文件中。

// Circle.h - a C++ class 
#ifndef CIRCLE_H
#define CIRCLE_H 
class Circle {
    public:
        Circle(float radius):_radius(radius) {}
        float getArea() { return 3.14159 * _radius * _radius; }
    private:
        float _radius;
}; 
#endif
现在让我们为此类声明一个C ++包装器,该包装器声明extern C方法,

可以在C中使用。此代码必须在C ++和C文件中进行编译。

使用void *指向类实例。 注意使用#ifdef __cplusplus。

/* Circle_C.h - must compile in both C and C++ */ 
#ifndef Circle_C_H
#define Circle_C_H 
    #ifdef __cplusplus
    extern "C" {
    #endif 
    extern void *Circle_C_new(float radius);
    extern void  Circle_C_delete(void *circle);
    extern float Circle_C_getArea(void *circle); 
    #ifdef __cplusplus
    }
    #endif 
#endif
现在定义外部函数。 这些只会编译为C ++,因此类

可以参考。

// Circle_C.cpp - extern C function definitions 
#include "Circle_C.h"
#include "Circle.h" 
extern void *Circle_C_new(float radius) {
    return new Circle(radius);
} 
extern void Circle_C_delete(void *circle) {
    Circle *c = (Circle *)circle;
    delete c;
} 
extern float Circle_C_getArea(void *circle) {
    Circle *c = (Circle *)circle;
    return c->getArea();
}
现在,我们可以使用这些extern C函数来从C访问C ++类。

是C主函数示例:

 /* mixed.c - a C file that accesses C++ methods */ 
#include <stdio.h>
#include "Circle_C.h" 
void main() {
    float radius = 1.5; 
    // Get a pointer to a Circle object
    void *circle = Circle_C_new(radius); 
    // Pass the Circle object to the wrapper methods
    float area = Circle_C_getArea(circle); 
    printf ("Circle of radius %f has area %f\n", radius, area); 
    // Free the Circle object memory
    Circle_C_delete(circle);
}
这是一个示例制作文件,用于创建“混合”可执行文件。
# Makefile - creates the executable "mixed".  Must link the stdc++ library 
mixed: main.o Circle.o
    gcc -lstdc++ -o mixed main.o Circle_C.o 
# Compile main as C
main.o: main.c
    gcc -c main.c -o main.o 
# Compile Circle_C as C++
Circle_C.o: Circle_C.cpp
    g++ -c Circle_C.cpp -o Circle_C.o
由...提交Jim Rogers

From: https://bytes.com/topic/c/insights/921728-calling-c-class-methods-c

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值