Why can't DLL function definitions be part of a class

I wanted to do something like this
1
2
3
4
5
6
7
8
9
10
11
12
13
    class DLLClass
    {
        DLLClass(){ pClass = 0; ]
        ~DLLClass(){ if (pClass) delete pClass; }

        extern "C"
        {
            __declspec(dllexport) DWORD __stdcall Init(char* DetailsArray[]);
            // several more exported functions 
        }

        AnotherClass* pClass;
    }

The idea was that I didn't want to export the whole class allowing the user to create instances of DLLClass, but I needed the pointer pClass to be deallocated automatically, so by creating an instance of DLLClass in dllmain the destructor would be called when dllmain exited and the pointer would be deallocated. The user would just call Init, then could call the other functions which use the pointer without allocating any memory themselves.

Why are extern "C" declarations inside of the class disallowed, and is there some other way I can achieve this same thing?
closed account (S6k9GNh0)
Because C has no idea what a class is.

C functions cannot:
* be overloaded.
* be in a struct (or C++ class for that matter) (however, a struct can hold pointers to a function).
* and something else I can't remember currently.
Ah of course, that makes sense thanks computerquip. Do you have any suggestions as to how I can achieve this without classes? I know I could just have a function that deletes the pointer but relying on the user to call this at the right time is probably a bad idea
closed account (S6k9GNh0)
Well, considering on your wants, I often do something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct api_Data {
    api_Data(AnotherClass* pClass) : m_pClass(pClass) {}
    
    AnotherClass* m_pClass;
};

extern "C" {

void* api_init() {
    return static_cast<void*>(new api_Data(nullptr));
}

void api_quit(void* handle) {
    delete static_cast<api_Data*>(handle);
}

}


api_init returns a handle to the underlying class, api_quit destroys that handle properly. Then you can make other C functions that do other stuff with the api_Data instance.
Last edited on
Topic archived. No new replies allowed.