C与C++从编译器的角度来说,是高度相关的,C++类可以直接用 C 的结构体实现,C可以直接呼叫 C++ 的类成员函数。比如这段代码
#include <iostream>
#include <stdio.h>
using namespace std;
#pragma pack (push, 1)
//we define 2 classes
class A {
private:
static uint8_t s;
uint8_t m1 = 3;
protected:
uint8_t m2 = 4;
public:
void add () { cout << m1 * m2 * s<<"\n";}
virtual void fun () {cout << "(-:<\n";}
};
uint8_t A::s = 10;
class B :public A {
public:
B():A(){}
uint8_t m3 = 5;
virtual void fun () {cout << ")-:<\n";}
};
//we define a C struct
struct sblock {
void ** fun;
uint8_t m1;
uint8_t m2;
uint8_t m3;
};
#pragma pack(pop)
typedef void (*c_fun) (void *);
int main(int /*argc*/, char * /*argv*/[])
{
//block is a struct
sblock block;
void * blockfun = ( void * ) &B::fun;
block.m1 = 3;
block.m2 = 4;
block.m3 = 5;
block.fun = &blockfun;
//we force a pointer convert
A * p = (A *) █
//call
p->add();
p->fun();
//we call a C++ function using C function pointer
A b;
c_fun cfun = (c_fun) &A::fun;
cfun (&b);
return 0;
}
输出结果为
120
)-:<
(-:<
在GNU C++编译器archlinux x64环境测试通过。对GNU C++编译器而言,这种测试尤为简单。对MSVC编译器,就复杂一些。因为windows下,C++ 的成员函数和 C 具有不同的栈操作。