Try something like this:
CDerived1 * d = (CDerived1*)pFactory("Derived1");
d->SomeMethod( );
In addition, use strcmp, stricmp, etc. instead of “==”.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I have a DLL where I have:
extern "C" __declspec(dllexport) CBase* __cdecl CreateInstance(const char* type)
{
if ("Derived1" == type)
return new CDerived1();
if ("Derived2" == type)
return new CDerived2();
return nullptr;
}
and in a console app, I am trying to use this function, loaded manually:
#include "MyDll.h"
typedef CBase* (*FACTORY)(const char* type);
HINSTANCE hInstance = LoadLibrary(_T("My.dll"));
if (nullptr != hInstance)
{
FACTORY pFactory = (FACTORY)GetProcAddress(hInstance, "CreateInstance");
if (pFactory)
{
pFactory->SomeMethod();
pFactory->OtherMethod();
}
FreeLibrary(hInstance);
}
I got:
error C2227: left of '->SomeMethod' must point to class/struct/union/generic type
What I have done wrong ?
Try something like this:
CDerived1 * d = (CDerived1*)pFactory("Derived1");
d->SomeMethod( );
In addition, use strcmp, stricmp, etc. instead of “==”.
I modified the code like this (the code is obvious, but because of late hours I missed):
FACTORY pFactory1 = (FACTORY)GetProcAddress(hInstance, "CreateInstance");
if (pFactory1)
{
CDerived1* pDerived1 = (CDerived1*)pFactory1("Derived1");
if (pDerived1)
{
pDerived1->SomeMethod();
pDerived1->Destroy();
}
}
FACTORY pFactory2 = (FACTORY)GetProcAddress(hInstance, "CreateInstance");
if (pFactory2)
{
CDerived2* pDerived2 = (CDerived2*)pFactory2("Derived2");
if (pDerived2)
{
pDerived2->SomeMethod();
pDerived2->Destroy(); // assert: File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp - Expression: __acrt_first_block == header
}
}
And Destroy() is defined in My.dll:
void Destroy() { delete this; }
Why I got that error ?
This is the code from DLL:
class CBase
{
private:
int object_id;
std::string type;
public:
CBase(const char* type)
{
this->type = type;
}
~CBase() {}
virtual void SomeMethod()
{
printf("CBase::SomeMethod");
}
};
class CDerived1 : public CBase
{
public:
explicit CDerived1(const char* type)
:CBase(type)
{
}
virtual void SomeMethod()
{
CBase::SomeMethod();
}
void Destroy() { delete this; }
};
class CDerived2 : public CBase
{
public:
explicit CDerived2(const char* type)
:CBase(type)
{
}
virtual void SomeMethod()
{
CBase::SomeMethod();
}
void Destroy() { delete this; }
};
extern "C" __declspec(dllexport) CBase* __cdecl CreateInstance(const char* type)
{
if ("Derived1" == type)
return new CDerived1();
if ("Derived2" == type)
return new CDerived2();
return nullptr;
}