Search code examples
c++cbackwards-compatibility

Allow my C++ library to work with C (reduced function sets)


I've been wanting to build a shared library of which will utilize classes to keep its functioning clean (it may require many inputs or processing), although I still wish to target for C platforms.

If I apply extern "C" {} over all my prototypes, and provide in example a set of exposed functions that mimick the class functions so that objects are not "required" to use my library, will those normal functions work in C programs that will link to it?


Solution

  • If you create a dll in the fasion you described, that is, all interfaces are extern "C" and all types in interfaces are POD's then yes, you'll practically have no problem using it in C or .NET

    Example:

    class MyClass
    {
     public:
        MyClass(float x) {...}
        void method(int x) {...}
        ~MyClass() {...}
    };
    
    #define MYAPI extern "C" __declspec(dllexport) //or whatever the syntax is for your compiler
    
    MYAPI MyClass* CreateMyClass(float x)
    {
        return new MyClass(x);    
    }
    
    MYAPI void MyClass_method(MyClass* p, int x)
    {
       return p->method(x);
    }
    
    MYAPI void DestroyMyClass(MyClass* p )
    {
       delete p;
    }