Let's say that I have the following code that's run in one thread of a multi-threaded COM application:
// Thread 1
struct foo {
int (*DoSomething)(void ** parm);
};
HMODULE fooHandle = LoadLibrary("pathToFoo");
typedef int (*loadUpFooFP)(foo ** fooPtrPtr);
loadUpFooFP loadUpFoo;
loadUpFoo = (loadUpFooFP)GetProcAddress(fooHandle, "fooLoader");
foo * myFoo;
loadUpFoo(&myFoo);
This all works great and I can then call
myFoo->DoSomething(&parmPtr);
This works, too! Now, another thread comes along and loads up its foo:
// Thread 2
foo * myFooInThread2;
loadUpFoo(&myFooInThread2);
And this, too, works great. In thread 2 I can call DoSomething:
// Thread 2
myFooInThread2->DoSomething(&anotherParmPtr);
Now, when thread 1 eventually goes away, I have a problem. I notice that debugging in Visual Studio that the address of DoSomething can no longer be evaluated. After the first thread dies, when I call:
myFooInThread2->DoSomething(&anotherParmPtr);
I get an access violation. The myFooInThread2 pointer is still valid, but the function pointer was not. This function pointer was set by a call into loadUpFoo which in turn was in a dll loaded by LoadLibrary.
My question is: where do I start looking for the reason this is failing? Is it some problem with the way the external DLL (that I load with LoadLibrary) is setting the function pointer in my foo struct? Or is it something to do with differing threads using the same library? Or, could it somehow be related to my usage of COM in this application (would calling CoUninitialize in the first thread somehow free this memory or library)?
I can provide more details on the COM setup if that looks like it could be responsible. Thanks!
edit: Thanks for the suggestions so far. The foo struct is opaque - I don't really know much about its implementation. The foo struct is declared in a header I import. There are no reference counting methods that I explicitly call and there are no other interactions with the library that's loaded with LoadLibrary. I'm pretty sure the foo struct is not memory mapped to some COM class, but like I said it's opaque and I can't say for sure.
The foo pointers' lifetimes are properly managed (not deleted).
The foo structure is an encryption library, so I'm not at liberty to divulge any more. At this point, I'm confident that there is nothing inherently wrong with my usage of LoadLibrary across different threads and within a COM application (and I suppose that the function pointer memory cleanup is being caused by something in the library itself outside of my control).