Search code examples
c++copencvcross-language

How I can access my C++ function in my C code or vice versa?


I want to implement a project in C, but it is comfortable to code some part of project in C++ and then call them from main C code.
Is it possible?! if yes, how I can do it?!
thanks in advance :)

P.S.
I used some libraries in my C++ Code such as OpenCV.


Solution

  • You'll need to "wrap" your C++ interface with regular C functions that take a parameter to indicate what object they'll be called on. For instance, if you have in C++

    class A
    {
        // .. boilerplate stuff...
        int SomeMethod(int n, float f);
    };
    

    Then along with it, you could declare a function such as

    extern "C" int A_SomeMethod(void* Obj, int n, float f)
    {
        return(((A*)Obj)->SomeMethod(n, f));
    }
    

    If you're not comfortable with the casting of the void*, you can implement some kind of map from an opaque handle to an A*. But the gist is you'll need to keep around some handle/pointer to the object that the method will be called on. In order to get the pointer/handle you'll need to wrap the allocation to:

    extern "C" void* A_Instantiate()
    {
        return new A;
    }
    

    The C++ files should be compiled separately along with the file with the functions above. A separate include for the C compilation should include declarations of all the functions above.

    EDIT: The caveats and comments below are important; to answer the question, "Yes it is possible to call C++ from C", and this is one approach. It's not a complete approach as there isn't really a mechanistic way to do it, but it's a start. Also, don't forget to create another call-through for delete, etc, etc.