C++ |DLL / EXE - 如何从导出的类调用另一个类方法?

C++ | DLL / EXE - How to call another class method from exported class?

本文关键字:调用 另一个 类方法 DLL EXE C++      更新时间:2023-10-16

我有一个项目,我想在其中使用 DLL。

我正在将工厂函数导出到我的 exe 中:

extern "C" __declspec(dllexport) 
BaseInit* __cdecl CreateInterface( void ) 
{
return new Initializer;
}

这非常有效。在我的 Init 类中,我有一个方法可以创建另一个类,我想从我的初始值设定项类方便地使用它:

class IAnotherClass {
public:
virtual void TestFunction();
...
class AnotherClass : public IAnotherClass {
public:
void TestFunction();
...
class Initializer : public BaseInit
{
IAnotherClass* Create(void)
{
return new AnotherClass;
}
...

这似乎也有效。我得到一个非空指针。但是,当尝试从此类(在我的exe程序中(调用TestFunction时,我得到:

LNK2001未解析的外部符号"公共:虚拟虚空__cdecl OtherClass::TestFunction(void(" (?TestFunction@AnotherClass@@UEAAXXZ(

void AnotherClass::TestFunction-body 在我的 DLL 项目中位于单独的 .cpp -文件中

我是否做错了,我实际上需要为每个不同的类实例提供单独的工厂函数?甚至有可能这样做吗?

您需要将__declspec(dllexport)添加到您希望在 dll 之外可用的每个类和函数,只要导出包含类,就不需要标记方法。

请注意,在类中,declspec 介于class和类名之间:

class __declspec(dllexport) Exported
{
};

您还需要定义一个宏,该宏根据您构建的是 dll 还是 exe,在__declspec(dllexport)__declspec(dllimport)之间切换标头,例如:

#ifdef BUILDING_MYDLL
#define MYDLL_EXPORT __declspec(dllexport)
#else
#define MYDLL_EXPORT __declspec(dllimport)
#endif
class MYDLL_EXPORT Exported
{
};