CSC 211 Study Guide: Windows Inter-Process Communication, Component Architectures, and the JavaScript Document Object Model
Dynamic Link Library (DLL)
Definition and Overview:
A Dynamic Link Library (DLL) is a modular, binary file format in Microsoft Windows (typically carrying a
.dllextension) that implements the concept of shared libraries.Rather than statically linking functions and data into an executable (
.exe) file at compile time, DLLs allow multiple software programs to share executable code, data, and resources simultaneously.Dynamic linking separates the executable binary from reusable functional libraries, reducing overall disk footprint and system memory consumption through shared memory mapping.
Core Architecture and Operational Mechanics:
Executable Structure: DLLs are formatted according to the Portable Executable (PE) specification used by Windows executables. They contain code sections (
.text), data sections (.data), export tables (.edata), and relocation sections (.reloc).Export and Import Address Tables:
Export Directory Table (EDT): Lists all functions, global variables, and symbols that the DLL makes available to other modules, accessible by function name or numerical index (ordinal).
Import Address Table (IAT): A lookup table maintained by the calling application that resolves external function addresses once the operating system's PE loader links the DLL.
Memory Sharing and Base Relocation:
When multiple processes invoke the same DLL, the Windows Virtual Memory Manager maps the physical memory pages containing the DLL's read-only code section into the virtual address spaces of all calling processes.
If two DLLs request the same preferred base address in virtual memory, the operating system executes base relocation by applying delta offsets stored in the relocation table to update absolute memory references.
Entry Point (
DllMain):An optional entry point function called by the operating system loader whenever a process or thread loads or unloads the DLL.
It accepts three arguments:
HINSTANCE hinstDLL(handle to the DLL module),DWORD fdwReason(the reason for calling), andLPVOID lpvReserved.Handled states include:
DLL_PROCESS_ATTACH: Invoked when a process first loads the DLL into its virtual address space.DLL_THREAD_ATTACH: Invoked when the host process creates a new thread.DLL_THREAD_DETACH: Invoked when a thread terminates cleanly.DLL_PROCESS_DETACH: Invoked when the DLL is unloaded from the process address space.
Types of Dynamic Linking:
Load-Time Dynamic Linking (Implicit Linking):
The host application specifies the exported DLL functions in an import library (
.lib) linked during compilation.The Windows loader automatically loads the DLL when the host application starts up; if the required DLL is missing, the application fails to launch.
Run-Time Dynamic Linking (Explicit Linking):
The application explicitly requests the operating system to load the DLL into memory during program execution using the Windows API.
Provides greater error recovery, as missing modules do not prevent program initialization.
How to Create a DLL:
Step 1: Define the Header File and Export Directives:
Declare exported functions using the Microsoft Visual C++ storage-class attribute
__declspec(dllexport).Use conditional preprocessor macros so that the header exports symbols when compiling the library and imports them (
__declspec(dllimport)) when compiled by client applications.Apply
extern "C"linkage in C++ projects to disable name mangling, ensuring consistent symbol names across different compilers.Step 2: Implement the Function Logic and
DllMain:Create the C or C++ source file implementing the exported functions.
Define the
DllMainroutine to handle resource allocation and cleanup during attachment and detachment events.Step 3: Compile and Link the Library:
Compile the source using an appropriate toolchain (such as MSVC
cl.exe /LD MathLibrary.cppor GCCgcc -shared -o MathLibrary.dll MathLibrary.c).The compiler and linker produce two primary output files: the dynamic library file (
MathLibrary.dll) and the companion import library (MathLibrary.lib).Step 4: Consume the DLL via Explicit Linking:
Call
LoadLibrary("MathLibrary.dll")orLoadLibraryEx()to map the module into the calling process.Call
GetProcAddress(hModule, "FunctionName")with the module handle and function name to retrieve the function's memory pointer.Cast the returned pointer to a matching function signature and invoke the function.
Call
FreeLibrary(hModule)when the library is no longer needed to decrement the module's reference count and release memory.
Dynamic Data Exchange (DDE)
Definition and Core Concept:
Dynamic Data Exchange (DDE) is an early inter-process communication (IPC) system developed by Microsoft for the Windows operating system.
It enables two or more simultaneously running Windows applications to share data and pass operational commands directly to one another using shared memory.
DDE relies heavily on the Windows messaging subsystem and global atom tables to establish and maintain inter-application dialogues.
Architectural Roles and Addressing Hierarchy:
Client and Server Roles:
DDE Server: The application that maintains data and makes it accessible to external processes.
DDE Client: The application that initiates the conversation, issues requests, and receives or modifies data hosted by the server.
Three-Tier Addressing Model:
Application (Service): The highest naming level, corresponding to the executable or service name of the server application (e.g.,
Excel,Progman).Topic: A logical data categorization or domain within the server, often representing a file name, document title, or general operational state (e.g.,
System,Sheet1.xlsx).Item: The granular unit of data queried or manipulated within a topic (e.g., a specific cell coordinate
R1C1or status queryStatus).
Conversation Types (Link Types):
Cold Link (Request on Demand):
The client issues a manual query for a specific data item.
The server extracts the data, transmits it to the client, and ends the active transaction without maintaining an automatic update loop.
Warm Link (Advise on Notification):
The client requests the server to notify it whenever the value of a target item changes.
When an update occurs, the server transmits a notification without sending the payload; the client decides whether and when to send a follow-up request to fetch the new data.
Hot Link (Continuous Push):
The client requests an automatic update subscription.
Whenever the data item changes on the server, the server immediately packages and pushes the updated data value to the client.
Underlying Message-Based Protocol:
Native DDE communication operates via specific Windows messages posted between application window message queues:
WM_DDE_INITIATE: Broadcast by the client to locate a server matching a given Application and Topic name.WM_DDE_ACK: Sent as an acknowledgment signal verifying receipt of a message or acceptance of a conversation.WM_DDE_REQUEST: Sent by a client to pull a single item value from the server.WM_DDE_DATA: Dispatched by the server to deliver raw data payloads stored in globally allocated memory (GlobalAlloc).WM_DDE_POKE: Dispatched by the client to inject unsolicited data values into the server's workspace.WM_DDE_ADVISE: Used to establish warm or hot links.WM_DDE_UNADVISE: Terminates an established advisory link.WM_DDE_EXECUTE: Sends a command string to be parsed and executed by the server application.WM_DDE_TERMINATE: Gracefully closes an active DDE channel.
How to Create a DDE Application (Using the DDEML API):
While raw DDE relies directly on window messaging, the Dynamic Data Exchange Management Library (DDEML) abstracts window message processing through high-level API functions and a central callback routine.
Step 1: Initialize the DDEML Framework:
Define a dedicated DDE callback function:
HDDEDATA CALLBACK DdeCallback(UINT uType, UINT uFmt, HCONV hconv, HSZ hsz1, HSZ hsz2, HDDEDATA hdata, ULONG_PTR dwData1, ULONG_PTR dwData2).Register the application with DDEML by calling
DdeInitialize(&idInst, DdeCallback, APPCMD_CLIENTONLY | CBF_FAIL_EXECUTES, 0).Step 2: Create String Handles:
DDE optimizes performance by converting textual strings into numerical handles (
HSZ).Call
DdeCreateStringHandle(idInst, "ServerName", CP_WINANSI)andDdeCreateStringHandle(idInst, "TopicName", CP_WINANSI)to generate service and topic identifiers.Step 3: Establish the Conversation:
Server-side: Register the service name globally using
DdeNameService(idInst, hszService, 0, DNS_REGISTER).Client-side: Establish a connection to the registered server and topic using
HCONV hConv = DdeConnect(idInst, hszService, hszTopic, NULL).Step 4: Execute Transactions:
Create an item string handle using
DdeCreateStringHandle(idInst, "ItemName", CP_WINANSI).To query data synchronously, invoke
DdeClientTransaction(NULL, 0, hConv, hszItem, CF_TEXT, XTYP_REQUEST, 5000, NULL).The server's callback routine intercepts the transaction type
XTYP_REQUEST, retrieves the requested data, encapsulates it viaDdeCreateDataHandle(), and returns the handle to the caller.Step 5: Terminate and Free Resources:
Disconnect the active channel via
DdeDisconnect(hConv).Free all generated string handles via
DdeFreeStringHandle(idInst, hszService).Unregister the application from DDEML using
DdeUninitialize(idInst).
Object Linking and Embedding (OLE)
Definition and Purpose:
Object Linking and Embedding (OLE) is a proprietary Microsoft technology built on the Component Object Model (COM).
It enables applications to create compound documents—documents containing content elements, media, and data created by independent, external server applications.
OLE eliminates the barrier between separate desktop tools by allowing an application (e.g., a word processor) to host interactive data structures (e.g., a spreadsheet or drawing) without native rendering or calculation support.
Linking versus Embedding:
Linked Objects:
The container document stores only a path reference (pointer) to an external file on the file system, alongside an optional static bitmap thumbnail.
The source data remains completely autonomous inside its original external file.
When the external file is modified, changes automatically propagate to the linked container document.
Keeps the container document file size minimal, but causes broken references if the source file is moved, renamed, or deleted.
Embedded Objects:
A complete snapshot copy of the source object's binary data is directly integrated and saved within the container document.
The container retains no persistent dependency on an external source file.
Modifying an embedded object alters only the copy inside the container and does not change any original source files.
Increases the overall container file size significantly because the embedded payload resides directly in the host file structure.
Key Features and Underlying Mechanisms:
In-Place Activation (Visual Editing):
When an embedded object is double-clicked inside a container document, the container's menus, toolbars, and interface dynamically transform into the menus and tools of the server application.
Users can edit the foreign object without launching a detached application window.
Structured Storage (Compound Files):
OLE relies on Structured Storage, commonly described as a "file system within a single file."
Files are partitioned into Storages (analogous to file directories) and Streams (analogous to raw files), allowing different applications to serialize objects into dedicated sections of a single file.
COM Interface Foundations:
IOleObject: The primary interface through which a container communicates with an embedded or linked object.IOleClientSite: The interface implemented by the container to give the embedded object access to its host context and visual boundaries.IOleInPlaceObjectandIOleInPlaceSite: Manage the coordinate mapping, activation, menu merging, and window handling for visual editing.IDataObject: Standardizes data transfer and clipboard operations using formats defined by theFORMATETCandSTGMEDIUMstructures.IStorageandIStream: Manage binary serialization within compound document storage files.
How to Create OLE Applications:
Programmatic Implementation via Microsoft Foundation Classes (MFC):
Creating an OLE Container Application:
Initialize the COM sub-libraries by calling
AfxOleInit()inside the application classInitInstance()method.Derive the document class from
COleDocumentrather than the standardCDocument.Derive an item class from
COleClientItemto manage each client-side embedded or linked object.Derive the view class from
COleClientItem-aware classes to manage selection borders, tracking rectangles, and in-place activation mouse triggers.
Creating an OLE Server / Component Application:
Initialize COM using
AfxOleInit().Derive the document class from
COleServerDoc.Derive an item class from
COleServerItem, overriding theOnDraw()method to render object contents into the container's device context.Derive an in-place frame window from
COleIPFrameWndto provide merged menu bars and toolbars during in-place activation.
User-Level Integration in Productivity Suites:
Launch the host container application (such as Microsoft Word).
Navigate to the Insert tab and locate the Object action within the Text tool grouping.
Choose between:
Create New: Select a registered COM class from the Object Type list to create an embedded object from scratch.
Create from File: Browse to an existing file and select either the Link option (creates an OLE Link) or leave it unselected (creates an OLE Embedded object).
Document Object Model (DOM) in JavaScript
Definition and Overview:
The Document Object Model (DOM) is an application programming interface (API) and platform-neutral, language-agnostic object representation of structured documents (HTML, XHTML, and XML).
When an HTML page is loaded, a web browser parses the raw markup and generates an in-memory tree of objects representing the document's structure, content, and stylistic rules.
JavaScript uses the DOM API to dynamically read, traverse, insert, modify, and delete HTML elements, attributes, and styles, turning static web documents into interactive software interfaces.
The DOM Tree Structure and Node Hierarchy:
The DOM represents an HTML document as a hierarchical tree composed of individual Nodes.
Global Object and Root Anchor:
The browser's global scope is the
windowobject.The
documentobject is a child property ofwindow(window.document) and serves as the single entry point to the entire DOM tree.The document root element is
document.documentElement, which maps directly to the top-level<html>tag.Core Node Classifications:
Document Node (
Node.DOCUMENT_NODE): The root container for the whole tree (node type value:).Element Node (
Node.ELEMENT_NODE): HTML tags that make up the structure, such as<div>,<p>, or<a>(node type value:).Text Node (
Node.TEXT_NODE): The actual textual content nested inside element nodes, including whitespace and line breaks (node type value:).Attribute Node (
Node.ATTRIBUTE_NODE): Historical representation of element properties likeclassorhref(node type value:). In modern standards, attributes are accessed through element methods rather than distinct tree nodes.Comment Node (
Node.COMMENT_NODE): Comments written within HTML source markup<!-- ... -->(node type value:).Document Fragment Node (
Node.DOCUMENT_FRAGMENT_NODE): A lightweight container for holding a sub-tree of nodes without a parent, commonly used for high-performance DOM manipulation (node type value:).
DOM Node Traversal and Relationships:
Nodes maintain bidirectional pointer relationships across the tree:
Parent Traversal:
node.parentNodeyields the immediate parent node;node.parentElementyields the parent only if it is an Element Node.Child Traversal (All Nodes):
node.childNodesreturns a liveNodeListcontaining all node types (including whitespace text nodes);node.firstChildandnode.lastChildpoint to the first and last child nodes.Child Traversal (Element Only):
node.childrenreturns anHTMLCollectioncontaining only Element Nodes;node.firstElementChildandnode.lastElementChildtarget the boundaries of element children.Sibling Traversal:
node.previousSiblingandnode.nextSiblingnavigate all neighboring nodes;node.previousElementSiblingandnode.nextElementSiblingnavigate exclusively between sibling elements.
Querying and Selecting DOM Elements:
Traditional Direct Query Methods:
document.getElementById("id"): Retrieves a single element matching the unique identifier attribute, ornullif not found.document.getElementsByTagName("tag"): Returns a liveHTMLCollectionof all elements matching the specified tag name.document.getElementsByClassName("class"): Returns a liveHTMLCollectionof all elements that include the specified class name.document.getElementsByName("name"): Returns a liveNodeListof elements matching thenameattribute (typically used for form controls).Modern Selector Query Methods (CSS Selectors):
element.querySelector("selector"): Evaluates a CSS selector string and returns the first matching element node, ornullif no match exists.element.querySelectorAll("selector"): Evaluates a CSS selector string and returns a static (non-live)NodeListof all matching elements.Comparison Note: Live collections (
HTMLCollection) update automatically when underlying DOM elements are added or deleted, whereas static collections (NodeListfromquerySelectorAll) capture a frozen snapshot of matching elements at the instant of execution.
Creating, Inserting, and Removing DOM Nodes:
Node Instantiation:
document.createElement("tagName"): Allocates a new element node in memory.document.createTextNode("textPayload"): Allocates a dedicated text node.document.createDocumentFragment(): Allocates an off-screen fragment container to stage multiple updates without triggering repeated document reflows.Insertion Methods:
parent.appendChild(newChild): AppendsnewChildas the last child ofparent.parent.insertBefore(newNode, referenceNode): InsertsnewNodedirectly ahead ofreferenceNodewithinparent.Modern convenience methods:
element.append(...nodesOrStrings): Appends multiple nodes or strings as children at the end.element.prepend(...nodesOrStrings): Inserts multiple nodes or strings as children at the start.element.before(...nodesOrStrings): Inserts items immediately before the targeted element.element.after(...nodesOrStrings): Inserts items immediately after the targeted element.element.replaceWith(newNode): Replaces the targeted element with a new node.
Removal and Cloning:
parent.removeChild(childNode): DetacheschildNodefromparentand returns the detached reference.element.remove(): Directly removes the element from its parent container in the DOM tree.element.cloneNode(deep): Clones an element. Ifdeepistrue, it clones the element and all nested descendants; iffalse, it copies only the opening element and its attributes.
Modifying Content, Attributes, and Styling:
Text and Markup Content:
element.textContent: Reads or sets the raw, unrendered text content of a node and all descendants; does not parse HTML tags, preventing Cross-Site Scripting (XSS) vulnerabilities.element.innerText: Reads or sets the visible rendered text, taking CSS styling (such asdisplay: none) and layout considerations into account.element.innerHTML: Reads or writes the raw HTML string inside an element; parsing a string assigned toinnerHTMLdynamically creates element nodes, but introduces security risks if handling unsanitized user input.Attribute Manipulation:
Standard methods:
element.getAttribute("name"),element.setAttribute("name", "value"),element.removeAttribute("name"), andelement.hasAttribute("name").Dataset API: Allows access to custom HTML5
data-*attributes viaelement.dataset.customProperty(mapping camelCase to kebab-case).Style and Class Manipulation:
Inline Styles: Manipulated via
element.style.propertyNameusing camelCase formatting (e.g.,element.style.backgroundColor = "red").Computed Styles: Accessed via
window.getComputedStyle(element), returning the final resolved CSS properties computed by the rendering engine.Class List API (
classList):element.classList.add("className"): Adds one or more classes.element.classList.remove("className"): Deletes specified classes.element.classList.toggle("className"): Adds the class if absent, or removes it if present.element.classList.contains("className"): Returns a boolean indicating whether the class is present.
The DOM Event Architecture:
The DOM implements an event-driven execution model that listens for and responds to user inputs (clicks, keypresses, scrolls) and system signals (network loads, rendering transitions).
The Three Event Propagation Phases:
Capture Phase (Trickling): The event travels downward from the root
window, throughdocumentand intermediate ancestor elements, toward the targeted element.Target Phase: The event reaches the actual element node that generated the event (
event.target).Bubbling Phase: The event bubbles upward from the target element through all its ancestral nodes back to the
windowroot.Event Registration and Handling:
element.addEventListener(type, listener, useCaptureOrOptions):type: String identifier of the event (e.g.,"click","keydown").listener: Callback function executed when the event fires.useCaptureOrOptions: Boolean (truefor capture phase,falsefor bubbling phase, defaults tofalse) or an options object ({ capture: false, once: true, passive: true }).
element.removeEventListener(type, listener): Detaches a previously bound listener (requires a stable function reference; anonymous functions cannot be removed).Event Object Mechanics:
When an event fires, the browser passes an
Eventobject to the callback function.event.target: Identifies the exact innermost DOM element where the event originated.event.currentTarget: Identifies the DOM element to which the active event handler is currently attached.event.preventDefault(): Cancels the browser's default behavior associated with the event (such as preventing a form from submitting or a link from navigating).event.stopPropagation(): Stops the event from propagating further up or down the DOM hierarchy.event.stopImmediatePropagation(): Prevents other event listeners bound to the exact same element from executing.Event Delegation Pattern:
Instead of binding separate event listeners to dozens of individual child elements, a single event listener is attached to their common parent.
Leveraging event bubbling, the parent intercepts events that bubble up from child elements and examines
event.targetto run conditional logic based on which child was clicked.Dramatically reduces memory consumption and automatically handles dynamically inserted child elements without requiring manual listener registration.
DOM Performance, Reflow, Repaint, and Page Lifecycle:
Rendering Pipeline Bottlenecks:
Reflow (Layout): The browser recalculates the precise physical geometry, size, and screen coordinates of elements. Triggered by layout-altering modifications such as changing widths, heights, margins, fonts, or querying dimensional properties (
offsetWidth,getBoundingClientRect()).Repaint: The browser updates the pixel colors of elements on screen without altering physical geometry (e.g., changes to
color,background-color, orvisibility). Repaints are computationally cheaper than reflows, but still impact frame rates.Optimization Strategies: Group DOM write and read operations to avoid layout thrashing; assemble complex sub-trees inside an off-screen
DocumentFragmentbefore appending them to the active document; toggle CSS classes rather than mutating multiple individual inline styles.Document Lifecycle Events:
DOMContentLoaded: Fires on thedocumentobject as soon as the HTML markup has been parsed and the DOM tree is constructed, without waiting for external stylesheets, images, or sub-frames to finish downloading.load: Fires on thewindowobject only after the HTML, DOM, and all dependent external resources (stylesheets, web fonts, images) have fully downloaded.beforeunloadandunload: Fire sequentially when the user navigates away from or closes the document, allowing cleanup or confirmation checks.