From: Peter Dimov (pdimov_at_[hidden])
Date: 2004-12-08 11:31:13


Dirk Gregorius wrote:
> Hi,
>
> is it possible to return a shared_ptr to an interface from a dl?. I
> thought of the following what unfortunately doesn't work:

[...]

> extern "C" InterfacePtr DLLCreate( void )
> {
> return InterfacePtr( new InterfaceImpl );
> }
>
> At the moment this code doesn't compile because VS7.1 complains that
> it a function with extern "C" linkage can't return a
> shared_ptr<Interface> instance. How could I implement the desired
> behavior?

Either omit the extern "C" or, if you must use a C-style interface, do this:

extern "C" Interface* DLLCreate()
{
    return new InterfaceImpl;
}

extern "C" void DLLDestroy( Interface* p )
{
    delete p;
}

and then construct an InterfacePtr( DLLCreate(), DLLDestroy ). You'll need a
public virtual destructor in this case, though.

> Some other related questions regarding this topic:
>
> 1.) I link to the multithreaded C run-time dll - is this allowed? I read
> in an older post that only static CRT linking is allowed.

Yes, it's allowed. Since you are using the DLL runtime, you probably don't
need to interoperate with different C++ compilers so you probably need to
just omit the extern "C" from DLLCreate.

> 2.) Does the above code - loading the factory from the DLL as well and
> (hopefully) constructing the instance there - solve the boundary
> problems? I read some articles regarding this issue, but to be honest
> I haven't completly understood the problems that may occure in this
> case so far.

Yes, it will work, as long as you don't unload the DLL that created the
object before destroying the object first (using FreeLibrary).