Search code examples
c++cclassextern

How to call a C++ method from C?


I have a C++ class and I'm compiling it with some C files.

I want to call a function which is defined in C++, actually in C++ class, so what am I going to do?

The following declarations to show what am I saying: there may there be syntax errors:

serial_comm.cpp

class MyClass {
    void sendCommandToSerialDevice(int Command, int Parameters, int DeviceId) {
         //some codes that write to serial port.
    }
}

external.c

int main(int argc, char ** argv) {
    //what am I going to write here?
}

Solution

  • The common approach to this problem is providing a C wrapper API. Write a C function that takes a pointer to a MyClass object (as MyClass is not valid C, you will need to provide some moniker, simplest one is moving void* around) and the rest of the arguments. Then inside C++ perform the function call:

    extern "C" void* MyClass_create() {
       return new MyClass;
    }
    extern "C" void MyClass_release(void* myclass) {
       delete static_cast<MyClass*>(myclass);
    }
    extern "C" void MyClass_sendCommandToSerialDevice(void* myclass, int cmd, int params, int id) {
       static_cast<MyClass*>(myclass)->sendCommandToSerialDevice(cmd,params,id);
    }
    

    Then the C code uses the C api to create the object, call the function and release the object:

    // C
    void* myclass = MyClass_create();
    MyClass_sendCommandToSerialDevice(myclass,1,2,3);
    MyClass_release(myclass);