Wednesday, February 23, 2011

Accessing C++ Classes from C credit to "Stephen Clamage"

Can we access a C++ class from C code? Can we declare a C struct that looks like a C++ class and somehow call member functions? 
The answer is yes, although to maintain portability you must add some complexity. Also, any modifications to the definition of the C++ class you are accessing requires that you review your C code.

We can have a C++ class such as the following:
class M {
public:
    virtual int foo(int);
    // ...private:
    int i, j;
};

We cannot declare class M in your C code. The best you can do is to pass around pointers to class M objects, like the way you deal with FILE objects in C Standard I/O. You can write extern "C" functions in C++ that access class M objects and call them from C code. Here is a C++ function designed to call the member function foo:
extern "C" int call_M_foo(M* m, int i) { return m->foo(i); }

Here is an example of C code that uses class M:
struct M; // you can supply only an incomplete declaration
int call_M_foo(struct M*, int); // declare the wrapper function
int f(struct M* p, int j) // now you can call M::foo
    { return call_M_foo(p, j); }

No comments:

Post a Comment

Thank you for Commenting Will reply soon ......

Featured Posts

#Linux Commands Unveiled: #date, #uname, #hostname, #hostid, #arch, #nproc

 #Linux Commands Unveiled: #date, #uname, #hostname, #hostid, #arch, #nproc Linux is an open-source operating system that is loved by millio...