Prior to refactoring my previous question, which I believe was a little bit off...

The title pretty much asks my question.

How can I keep a class definition on it's own without giving it methods & producing the error below?

The reason for this is because I want to create an object in a separate DLL (which contains the methods), but only return a reference pointer to my main program. This is explicit exporting by the way.

Error 1 error LNK2001: unresolved external symbol "public: int __thiscall ObjTest::getValue(void)" (?getValue@ObjTest@@QAEHXZ)

class ObjTest
{
private:
    int x;
public:
    int getValue();
};
有帮助吗?

解决方案

Since you need to load the .dll with LoadLibrary(), you can expose a pure virtual class, and have the .dll return a sub class of it:

You separate them in two files:

File ObjTest.h:

class ObjTest
{

public:
    virtual int getValue() = 0;
};
ObjTest *CreateObjTest();

File ObjTest.cpp:

#include "ObjTest.h"

class ObjTestImpl : public ObjTest
{
    int x;
public:
    virtual int getValue();
};

int ObjTestImpl::getValue()
{
   return x;
}
ObjTest *CreateObjTest()
{
  return new ObjTestImpl();
}

You compile ObjTest.cpp and create a .dll out of it. Your main executable program will need to LoadLibrary() your .dll, use GetProcAddress() to extract the CreateObjTest as a function pointer and call it to return a new ObjTest .

(You might have to create a DeleteObjTest() function too - if your main executable and .dll end up with a different CRT, they'll have different heaps, so you need to call into the .dll instead of just doing delete myObj.)

The other approach is to wrap everying in a C API, and just pass opaque handles to C functions across the .dll instead of dealing with C++ objects.

其他提示

You are confusing definition and implementation. You have the method defined but not implemented. Hence, the compiler compiles the code without error, as the method is defined, the linker creates an error as there is no implementation for the method (undefined symbol).

The DevStudio compiler does let you import classes from DLLs into an application:-

class __declspec (dllimport) ClassName
{
  // members, etc
}

and in the DLL source, change the 'dllimport' to 'dllexport'.

See this MSDN article for more information.

If you want to hide the data members and the private methods then you'd need to look into the pimpl idiom.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top