1
我正在寫返回指向基類的動態庫返回,但我想他們垂頭喪氣派生類。例如:溯造型類型從動態庫
//Library code:
class A
{
public:
A(void) = default;
virtual ~A(void) = default;
virtual void Foo(void)
{
std::cout << "A::Foo\n";
};
};
class B : public A
{
public:
B(void) = default;
void Foo(void) override
{
std::cout << "B::Foo\n";
}
virtual void Bar(void)
{
std::cout << "B::Bar\n";
}
};
class Factory
{
public:
Factory(void) = default;
virtual std::shared_ptr<A> CreateB(void)
{
return std::shared_ptr<A>{new B{}};
}
};
extern "C" std::shared_ptr<Factory> CreateFactory(void)
{
return std::make_shared<Factory>();
}
//Application code:
int main(int argc, char* argv[])
try
{
auto handle = dlopen("./Dynamic.so", RTLD_LAZY);
if (handle == nullptr)
{
throw std::runtime_error{dlerror()};
}
auto factoryaddress =
reinterpret_cast<std::shared_ptr<Factory>(*)(void)>(
dlsym(handle, "CreateFactory"));
if (factoryaddress == nullptr)
{
dlclose(handle);
throw std::runtime_error{dlerror()};
}
auto factory = factoryaddress();
auto a = factory->CreateB();
a->Foo();
auto b = std::dynamic_pointer_cast<B>(a);
b->Bar();
std::cin.get();
}
我得到
/usr/include/c++/5/bits/shared_ptr.h:458: undefined reference to `typeinfo for B'
/usr/include/c++/5/bits/shared_ptr.h:458: undefined reference to `typeinfo for A'
是的,在我的測試情況下,我把定義在一個單獨的文件。我會嘗試你的建議。 – Lyberta
我可以在導出的類中使用純虛函數嗎? – Lyberta
是的。純粹的虛擬功能就像主題內聯一樣行事。沒有純虛函數的二進制定義可用於確定哪個對象文件是該類的主要實現者。 –