MFC › 7. Data, System and Interop
DLLs, ActiveX and COM
Regular vs extension DLLs and using COM from MFC.
Explanation
MFC DLLs
| Kind | What it exports | MFC use |
|---|---|---|
| Regular DLL | plain functions (extern "C") with a C interface; callable from any language |
has its own CWinApp and MFC state; may link MFC statically or dynamically |
| Extension DLL | C++ classes and functions that use MFC types in their interface (AFX_EXT_CLASS) |
always uses the shared MFC DLL; the .exe must too; DllMain calls AfxInitExtensionModule and creates a CDynLinkLibrary |
Module state: an MFC DLL has its own resource handle, handle maps and so on. In every exported function of a regular DLL put AFX_MANAGE_STATE(AfxGetStaticModuleState()); as the first line, or MFC looks for resources and windows in the caller’s module. An extension DLL doesn’t need it, but its CDynLinkLibrary object makes the DLL’s resources reachable through the application.
A DLL that is used by a program written with another compiler or language must export a C interface with a fixed calling convention (__stdcall) and plain types; never pass CString, STL types or C++ exceptions across it (different CRT/ABI).
COM / ActiveX
COM is Windows’ binary object model: objects implement interfaces (IUnknown with reference counting, IDispatch for scripting). Automation (Excel, Word, WMI, scripting) uses IDispatch; ActiveX controls are COM objects with a UI.
Helpers (ATL, header <atlbase.h>): CComPtr<T> (smart interface pointer, calls Release), CComBSTR (BSTR strings), CComVariant (VARIANT), CComDispatchDriver (call methods by name). CoInitializeEx must run on each thread that uses COM. In MFC, AfxOleInit() does this and enables OLE features. The #import "file.tlb" directive generates wrapper classes from a type library.
Example
Exported function of a regular DLL, and an extension DLL:
#include <afxwin.h>
#include <afxdllx.h>
// ---------- regular DLL ----------
class CGreetDllApp : public CWinApp {
public:
BOOL InitInstance() override { return CWinApp::InitInstance(); }
};
CGreetDllApp theDllApp; // a regular DLL has its own CWinApp object
extern "C" __declspec(dllexport) int __stdcall ShowGreeting(const wchar_t* name) {
AFX_MANAGE_STATE(AfxGetStaticModuleState()); // FIRST LINE of every exported function
CString s;
s.Format(_T("Hello, %s!"), name);
AfxMessageBox(s); // finds THIS DLL's resources, not the caller's
return s.GetLength();
}
// ---------- extension DLL (a different project: shown together for brevity) ----------
static AFX_EXTENSION_MODULE extensionDll = { false, nullptr };
extern "C" int APIENTRY ExtDllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID) {
if (dwReason == DLL_PROCESS_ATTACH) {
if (!AfxInitExtensionModule(extensionDll, hInstance)) return 0;
new CDynLinkLibrary(extensionDll); // adds the DLL to the app's resource search chain
} else if (dwReason == DLL_PROCESS_DETACH) {
AfxTermExtensionModule(extensionDll);
}
return 1;
}
class AFX_EXT_CLASS CShapeHelper { // exported C++ class using MFC types
public:
static CString Describe(const CRect& rc) {
CString s;
s.Format(_T("%d x %d"), rc.Width(), rc.Height());
return s;
}
};
(In a real extension DLL the entry point is named DllMain. It is renamed here only so both examples fit in one file.)
Using COM by name through automation, as a console program (the Scripting Runtime ships with Windows):
#include <afxwin.h>
#include <atlbase.h>
#include <iostream>
int _tmain() {
if (!AfxWinInit(::GetModuleHandle(nullptr), nullptr, ::GetCommandLine(), 0)) return 1;
HRESULT hr = ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); // every COM thread needs this
if (FAILED(hr)) return 1;
{
CComDispatchDriver fso; // IDispatch smart pointer
hr = fso.CoCreateInstance(L"Scripting.FileSystemObject");
if (SUCCEEDED(hr)) {
CComVariant path(L"C:\\Windows");
CComVariant result;
hr = fso.Invoke1(L"FolderExists", &path, &result); // call a method by name
if (SUCCEEDED(hr))
std::wcout << L"C:\\Windows exists: " << (result.boolVal != VARIANT_FALSE) << L"\n";
CComBSTR joined; // BSTR string
CComVariant a(L"C:\\Temp"), b(L"file.txt");
CComVariant joinedResult;
if (SUCCEEDED(fso.Invoke2(L"BuildPath", &a, &b, &joinedResult)) && joinedResult.vt == VT_BSTR)
std::wcout << joinedResult.bstrVal << L"\n";
} else {
std::wcout << L"CoCreateInstance failed: 0x" << std::hex << hr << L"\n";
}
} // smart pointers release here
::CoUninitialize(); // must follow all COM object releases
return 0;
}
Common pitfalls
- Missing
AFX_MANAGE_STATEin regular-DLL exports: dialogs show without resources,AfxMessageBoxasserts,AfxGetApp()returns the wrong app. - Mixing CRTs/ABIs: freeing memory in the .exe that was allocated in a DLL built with a different runtime corrupts the heap; export a
Freefunction or use the shared runtime for both. CString/std::stringin a DLL’s exported C interface ties it to the exact MFC/STL version; keep exported APIs to C types.- Forgetting
CoUninitialize, or releasing a COM pointer afterCoUninitialize, crashes. Put COM objects in an inner scope. - Leaking
BSTRs andVARIANTs: useCComBSTR/CComVariant; callSysFreeString/VariantClearfor raw ones. - Threading model: an object created in an STA must be called from that thread, or through a marshaled proxy.
LoadLibrary+FreeLibraryof an MFC DLL while the application still holds objects from it unloads their vtables: crash.- 32-bit and 64-bit processes cannot load each other’s DLLs. Build both.
Legacy vs modern
ActiveX controls (embedded in Internet Explorer, VB6, Office) are largely obsolete. COM itself remains central in Windows (DirectX, shell APIs, WinRT). Modern C++ for COM uses WRL and C++/WinRT (winrt::com_ptr). A DLL’s stable boundary today is often a C API, with the Pimpl idiom hiding the classes.
Exercises
1. Which DLL type do you choose to export a class that derives from CDialog to an MFC application?
An extension DLL: it shares the MFC DLL with the application so MFC classes can cross the boundary. A regular DLL isolates MFC and exports only C functions.