Introduction
If you try to dynamically use a class exported from a .dll sometimes you get an
ugly error because you try to release memory allocated by some other heap
manager. For example, you create the object using a factory method and release
it calling delete directly. In this case the heap is allocated by the .dll's
heap manager and the .exe's heap manager throws an exception when you try to
release it.
There are two methods to counter this problem. The easiest is to set Project ->
Properties -> Code Generation -> Runtime Library to Multi-threaded Debug DLL
both in the .exe and in the .dll.
If you can't do this for whatever reason you have a second option: you must
free the memory in the same module (.dll or .exe) in which you have allocated it.
The following code shows how to do it:
#pragma once
#ifdef D1_EXPORTS
#define D1API __declspec(dllexport)
#else
#define D1API __declspec(dllimport)
#endif
class D1API A1
{
public:
int x;
static A1* New();
static void Delete(A1* a1);
};
#include "a1.h"
A1* A1::New()
{
return new A1;
}
void A1::Delete(A1* a1)
{
delete a1;
}
#include "../d1/A1.h"
int main()
{
A1 a1;
a1.x = 10;
A1* a2 = new A1; a2->x = 20;
delete a2;
A1* a3 = A1::New(); a3->x = 30;
A1::Delete(a3);
A1* a4 = new A1;
a4->x = 40;
A1::Delete(a4);
A1* a5 = A1::New();
a5->x = 50;
delete a5;
return 0;
}