This program shows how you can access the data members in C++ classes from source code written in C.
The program consists of these files:
See Figure 199.
Figure 199. C++ Source File hourclas.cpp Definitions Used by C Source File hour.c
#include <iostream.h>
class HourMin { // base class
protected:
int h;
int m;
public:
void set_hour(int hour) { h = hour % 24; } // keep it in range
int get_hour() { return h; }
void set_min(int min) { m = min % 60; } // keep it in range
int get_min() { return m; }
HourMin(): h(0), m(0) {}
void display() { cout << h << ':' << m << endl; }
};
// derived from class HourMin
class HourMinSec1 : public HourMin {
public:
int s;
void set_sec(int sec) { s = sec % 60; } // keep it in range
int get_sec() { return s; }
HourMinSec1() { s = 0; }
void display() { cout << h << ':' << m << ':' << s << endl; }
};
// has an HourMin contained inside
class HourMinSec2 {
private:
HourMin a;
int s;
public:
void set_sec(int sec) { s = sec % 60; } // keep it in range
int get_sec() { return s; }
HourMinSec2() { s = 0; }
void display() {
cout << a.get_hour() << ':' << a.get_min() << ':' << s << endl; }
};
extern "C" void CSetHour(HourMin *); // defined in C
extern "C" void CSetSec(HourMin *); // defined in C
extern "C" void CSafeSetHour(HourMin *); // defined in C
// wrapper function to be called from C code */
extern "C" void CXXSetHour(HourMin * x) {
x->set_hour(99); // much like the C version but the C++
// member functions provide some protection
// expect 99 % 24, or 3 to be the result
}
// other wrappers may be written to access other member functions
// or operators ...
main() {
HourMin hm;
hm.set_hour(18); // supper time;
CSetHour(&hm); // pass address of object to C function
hm.display(); // hour is out of range
HourMinSec1 hms1;
CSetSec((HourMin *) &hms1)
hms1.display();
HourMinSec2 hms2;
CSetSec(&hms2);
hms2.display();
CSafeSetHour(&hm); // pass address to a safer C function
hm.display(); // hour is not out of range
}
|
Figure 200. C Source file hour.c that Uses Definitions from C++ Source File hourclas.cpp
|
As shown in Figure 199, the main() C++ function:
The program output is:
+--------------------------------------------------------------------------------+ |99:0 | |0 -:0 :45 | |0 -:0 :45 | |3 -:0 | |Press ENTER to end terminal session. | +--------------------------------------------------------------------------------+
(C) Copyright IBM Corporation 1992, 2005. All Rights Reserved.