Click to See Complete Forum and Search --> : Allocating memory in managed, freeing in unmanaged


scier
March 19th, 2003, 06:56 PM
I'm having a problem freeing an instance of an unmanaged C++ class in an unmanaged DLL which I allocated in a managed C++ application. The reason I need to do this is that I'm using an unmanaged DLL which employs reference counting -- so the objects free themselves. Rewriting the DLL in managed code is not an option; recompiling it is a very last resort.

The symptom is that the heap becomes corrupt while in the destructor of the object in question; a dialog pops up with the following:

Debug Assertion Failed!

Program: [...]
File: dbgheap.c
Line: 1132
Expression: _CrtIsValidHeapPointer(pUserData)


This occurs after entering the destructor but before control returns to the unmanaged code which called delete. I've culled this down to a few classes exhibiting the behaviour reliably.

Unmanaged DLL header (sans #includes etc):

class __declspec(dllexport) Foo {
public:
Foo();
~Foo();
};

class __declspec(dllexport) FooUtil {
public:
static void DeleteFoo(Foo *o);
};


Unmanaged DLL code (sans #includes etc):

Foo::Foo() { std::cout << "Foo()" << std::endl; }
Foo::~Foo() { std::cout << "~Foo()" << std::endl; }

void FooUtil::DeleteFoo(Foo *o) {
std::cout << "FooUtil::DeleteFoo()" << std::endl;
delete o;
std::cout << "FooUtil::DeleteFoo() complete" << std::endl;
}


Managed C++ application code (sans #includes etc):

int _tmain(void)
{
Foo *foo = new Foo();
FooUtil::DeleteFoo(foo);
return 0;
}


Output:

Foo()
FooUtil::DeleteFoo()
~Foo()
[dialog pops up]


This is all compiled with MSVC.NET 7.0, with .NET Framework 1.0 SP 2. The projects were created with the new-project wizard as 'MFC DLL' and 'Unmanaged Application'.

Any ideas?

-spc