How to export a static object from a DLL
Dear VC programmers,
I am implementing factory using LoadLibrary and I got a problem
exporting a static object. Here is the example.
// BaseShape.h
#ifndef _BaseShape_H_
#define _BaseShape_H_
#include <string>
#include <map>
class BaseShape {
public:
virtual void draw()=0;
};
typedef BaseShape* (*CreatorTyp)();
typedef std::map<std::string, CreatorTyp> ShapeFactoryTyp;
// global factory registry
extern __declspec( dllexport )ShapeFactoryTyp factory;
#endif
// libCircle.dll: Circle.h Circle.cpp Circle.def
// Circle.h
#ifndef _Circle_H_
#define _Circle_H_
#include "BaseShape.h"
class Circle : public BaseShape {
public:
void draw();
};
#endif
//Circle.cpp
#include "Circle.h"
#include <iostream>
void Circle::draw() {
std::cout << "Circle" << std::endl;
}
extern "C" {
BaseShape* create() {
return new Circle;
}
}
class CircleProxy {
public:
CircleProxy() {
factory["Circle"]=create;
}
~CircleProxy() {
ShapeFactoryTyp::iterator itr=factory.find("Circle");
if (itr!=factory.end()) {
factory.erase(itr);
}
}
};
// proxy to register create() to factory
static CircleProxy cp;
// Circle.def
export create
// test.cpp
#include "BaseShape.h"
#include <windows.h>
#include <cstdlib>
#include <iostream>
ShapeFactoryTyp factory; // factory definition
int main(int argc, char* argv[]) {
HINSTANCE hinstLib;
hinstLib = LoadLibrary(TEXT("libCircle.dll"));
if (hinstLib) {
if (factory.begin() != factory.end())
return EXIT_SUCCESS;
}
else
{
int errCode=(int)GetLastError();
std::cout << "errCode=" << errCode << std::endl;
}
return EXIT_FAILURE;
}
My questions are:
How can I export cp so that it is initialized when libCircle is
loaded?
Which link options I should use?
Thanks,
YE LIU