Search code examples
c++coopconstructordllexport

Making an object from a C dll in C++


I have a C++ program which I call multiple C++ Dlls in it. Usually I make a simple class in the Dlls with a constructor and a destructor and do some initialization in the constructors. Then in the main program I make multiple objects from each Dlls' class and use them in multiple threads.

MyNamespcae::MyDllClass * MyObj = new MyNamespcae::MyDllClass(/*...inputs...*/);  # I make an object for each thread seperately

Now I have a C Dll that I'm calling in the main c++ program. I exported the C functions with __declspec(dllexport) and use them directly in the main program. The problem here is that I have some global variables in the C Dll, so I can not use the Dll in multiple threads.

So my question is how can I do some object-oriented-like method (like what we do in C++) in the C dll to call it in C++, from multiple threads? (Note My question is about what I need to do in C not c++)


Solution

  • The link shared by Lorinczy Zsigmond which is: http://lzsiga.users.sourceforge.net/oop.html#S0004 solved my problem. I repeat it's content here for more convenience:

    Header-file: /* mytype.h */

    #ifndef MYTYPE_H
    #define MYTYPE_H
    
    typedef struct MyType MyType; /* opaque */
    
    MyType *MyType_Alloc (int par);
    void    MyType_Release (MyType *mp);
    
    int MyType_Operation1 (MyType *mp, int par1, int par2);
    
    #endif
    

    source code: /* mytype.c */

    #include <stdlib.h>
    #include <string.h>
    
    #include "mytype.h"
    
    struct MyType {
        int somedata;
    };
    
    MyType *MyType_Alloc (int par) {
        MyType *mp= malloc (sizeof *mp);
        mp->somedata= par;
        return mp;
    }
    
    void MyType_Release (MyType *mp) {
        memset (mp, 0, sizeof *mp);
        free (mp);
    }
    
    int MyType_Operation1 (MyType *mp, int par1, int par2) {
        return mp->somedata + par1 + par2;
    }
    

    test:/* mytypetest.c */

    #include <stdio.h>
    
    #include "mytype.h"
    
    int main (void) {
        MyType *mp= MyType_Alloc (20200000);
        int sum= MyType_Operation1 (mp, 100, 25);
        printf ("sum=%d\n", sum);
        MyType_Release (mp);
        return 0;
    }