Search code examples
c++boostdlldllimportdllexport

Is it possible to instantiate an object in a client if it's defined in a DLL/Lib?


I couldn't come up with a more proper name for the question, but I think it'll be clear with the examples below.

What is the fundamental difference (memory-wise) between:

  1. A DLL that contains the following code:

    class ISDLConsole { /* interface */ };
    class SDLConsole: public ISDLConsole { /* implementation */ };
    __declspec(dllexport) ISDLConsole *Create()
    {
        return new SDLConsole();
    }
    

    with a client that has linked dynamically with this DLL and called:

    ISDLConsole * pClientSDLConsole = Create();
    
  2. A client of boost, that links with it dynamically, and uses one of their containers as follows:

    boost::numeric::ublas::vector<double> v(1000);

Now, if I didn't already assume something wrong, it seems to me that in both cases there is a client that is linked with a DLL, invokes a method (in the boost case it's the vector::vector() c'tor) which allocates dynamic memory.

I assume that it would be better to replace ISDLConsole * pClientSDLConsole = Create(); with ISDLConsole * pClientSDLConsole = new SDLConsole(); (export the class itself if possible) and allocate memory only on the client side, right?

So:

  • What is the fundamental difference (memory-wise) between 1 and 2? are both cases the same in terms of memory-accorss-dlls? if so, please clarify how.
  • If they're not the same, why would someone recommend allocating a new object across DLL and not do it the 'boost' way I mentioned above (if possible).
  • If I want to write my own container and put it in a separate DLL, what parts of it should be '__declspec(dllexport)ed'? and does it mean there will be memory moving across DLLs (assuming my container allocates dynamic memory)?

Any clarifications on the subject are more than welcome. Thank you very much.

The source for the ISDLConsole example is this accepted answer, which BTW contradicts this accepted answer.


Solution

  • In terms of heap allocation, I see no difference. In both cases, you get a class instance allocated on the heap. An instantiated object in the heap should take up the same amount of memory whether or not it was instantiated in them main executable, or a library.

    In terms of code, I would expect to be a few bytes' worth of difference, between the two approaches. Background noise, nothing I would be concerned with.