CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-comtypes

Pure Python COM package for Windows COM automation and interoperability

88

0.98x
Overview
Eval results
Files

automation.mddocs/

Automation and IDispatch

COM automation support for interacting with automation servers like Microsoft Office applications. Provides VARIANT handling, dispatch interfaces, type conversion, and late-bound method invocation capabilities.

Capabilities

Dispatch Interface

Primary interface for COM automation that enables late-bound method and property access through dispatch identifiers.

class IDispatch(IUnknown):
    """Standard automation interface for late-bound COM object access."""
    
    def GetTypeInfoCount(self):
        """
        Get number of type information interfaces.
        
        Returns:
            int: Number of type info interfaces (0 or 1)
        """
    
    def GetTypeInfo(self, itinfo, lcid):
        """
        Get type information interface.
        
        Args:
            itinfo (int): Type info index (usually 0)
            lcid (int): Locale identifier
        
        Returns:
            ITypeInfo: Type information interface
        """
    
    def GetIDsOfNames(self, names, lcid=0):
        """
        Map member names to dispatch identifiers.
        
        Args:
            names (list): List of member names
            lcid (int, optional): Locale identifier
        
        Returns:
            list: List of dispatch IDs
        
        Raises:
            COMError: If name not found (DISP_E_UNKNOWNNAME)
        """
    
    def Invoke(self, dispid, lcid, flags, args, named_args=None):
        """
        Invoke method or access property by dispatch ID.
        
        Args:
            dispid (int): Dispatch identifier
            lcid (int): Locale identifier
            flags (int): Invocation flags (INVOKE_METHOD, INVOKE_PROPERTYGET, etc.)
            args (tuple): Positional arguments as VARIANTs
            named_args (dict, optional): Named arguments
        
        Returns:
            VARIANT: Return value
        
        Raises:
            COMError: If invocation fails
        """

VARIANT Type System

Universal data type for COM automation that can hold various data types with automatic conversion support.

class VARIANT:
    """Universal data type for COM automation."""
    
    def __init__(self, value=None, vt=None):
        """
        Create VARIANT from Python value.
        
        Args:
            value: Python value to convert
            vt (int, optional): Explicit variant type (VT_ constant)
        """
    
    @property
    def vt(self):
        """Get variant type (VT_ constant)."""
    
    @property
    def value(self):
        """Get Python value from VARIANT."""
    
    def __bool__(self):
        """Boolean evaluation of VARIANT."""
    
    def __str__(self):
        """String representation of VARIANT value."""
    
    def __eq__(self, other):
        """Compare VARIANTs for equality."""

class tagVARIANT:
    """Low-level VARIANT structure."""
    vt: int        # Variant type
    wReserved1: int # Reserved
    wReserved2: int # Reserved  
    wReserved3: int # Reserved
    # Union of all possible values
    llVal: int     # 8-byte integer
    lVal: int      # 4-byte integer
    bVal: int      # 1-byte value
    iVal: int      # 2-byte integer
    fltVal: float  # 4-byte float
    dblVal: float  # 8-byte double
    boolVal: int   # Boolean value
    scode: int     # SCODE value
    cyVal: object  # Currency value
    date: float    # DATE value
    bstrVal: str   # BSTR string
    punkVal: object # IUnknown pointer
    pdispVal: object # IDispatch pointer
    parray: object  # SAFEARRAY pointer

VARIANT Type Constants

Constants defining the data types that can be stored in VARIANT structures.

# Basic types
VT_EMPTY: int       # 0 - No value
VT_NULL: int        # 1 - Null value
VT_I2: int          # 2 - 2-byte signed integer
VT_I4: int          # 3 - 4-byte signed integer
VT_R4: int          # 4 - 4-byte float
VT_R8: int          # 5 - 8-byte double
VT_CY: int          # 6 - Currency
VT_DATE: int        # 7 - Date/time
VT_BSTR: int        # 8 - Basic string
VT_DISPATCH: int    # 9 - IDispatch pointer
VT_ERROR: int       # 10 - SCODE error code
VT_BOOL: int        # 11 - Boolean value
VT_VARIANT: int     # 12 - VARIANT pointer
VT_UNKNOWN: int     # 13 - IUnknown pointer
VT_DECIMAL: int     # 14 - Decimal value

# Extended types
VT_I1: int          # 16 - 1-byte signed integer
VT_UI1: int         # 17 - 1-byte unsigned integer
VT_UI2: int         # 18 - 2-byte unsigned integer
VT_UI4: int         # 19 - 4-byte unsigned integer
VT_I8: int          # 20 - 8-byte signed integer
VT_UI8: int         # 21 - 8-byte unsigned integer
VT_INT: int         # 22 - Native integer
VT_UINT: int        # 23 - Native unsigned integer
VT_VOID: int        # 24 - Void type
VT_HRESULT: int     # 25 - HRESULT value
VT_PTR: int         # 26 - Pointer type
VT_SAFEARRAY: int   # 27 - SAFEARRAY
VT_CARRAY: int      # 28 - C-style array
VT_USERDEFINED: int # 29 - User-defined type
VT_LPSTR: int       # 30 - ANSI string pointer
VT_LPWSTR: int      # 31 - Unicode string pointer
VT_RECORD: int      # 36 - Record type
VT_INT_PTR: int     # 37 - Integer pointer
VT_UINT_PTR: int    # 38 - Unsigned integer pointer

# Extended types
VT_FILETIME: int    # 64 - FILETIME
VT_BLOB: int        # 65 - Binary large object
VT_STREAM: int      # 66 - Stream interface
VT_STORAGE: int     # 67 - Storage interface
VT_STREAMED_OBJECT: int  # 68 - Streamed object
VT_STORED_OBJECT: int    # 69 - Stored object
VT_BLOB_OBJECT: int      # 70 - BLOB object
VT_CF: int          # 71 - Clipboard format
VT_CLSID: int       # 72 - Class ID
VT_VERSIONED_STREAM: int # 73 - Versioned stream
VT_BSTR_BLOB: int   # 4095 - BSTR blob
VT_VECTOR: int      # 4096 - Vector flag
VT_ILLEGAL: int     # 65535 - Illegal value
VT_ILLEGALMASKED: int    # 4095 - Masked illegal value
VT_TYPEMASK: int    # 4095 - Type mask

# Array and reference flags
VT_ARRAY: int       # 0x2000 - Array flag
VT_BYREF: int       # 0x4000 - Reference flag
VT_RESERVED: int    # 0x8000 - Reserved flag

Invocation Constants

Constants for specifying how dispatch methods and properties should be invoked.

# Invocation kinds
INVOKE_FUNC: int            # 1 - Invoke as method
INVOKE_PROPERTYGET: int     # 2 - Get property value
INVOKE_PROPERTYPUT: int     # 4 - Set property value
INVOKE_PROPERTYPUTREF: int  # 8 - Set property by reference

# Dispatch flags
DISPATCH_METHOD: int        # 1 - Method invocation
DISPATCH_PROPERTYGET: int   # 2 - Property get
DISPATCH_PROPERTYPUT: int   # 4 - Property put
DISPATCH_PROPERTYPUTREF: int # 8 - Property put by reference

String Types

Specialized string types for COM automation with proper memory management.

class BSTR:
    """
    The Windows BSTR data type for COM automation strings.
    
    A length-prefixed Unicode string type used by COM automation.
    Inherits from ctypes._SimpleCData for proper COM memory management.
    """
    def __init__(self, value=None): ...
    def __repr__(self): ...
    def __ctypes_from_outparam__(self): ...

Locale Support

Locale identifier type for internationalization support in automation.

LCID = int  # Type alias for locale identifier

# Common locale identifiers
LOCALE_SYSTEM_DEFAULT: int    # System default locale
LOCALE_USER_DEFAULT: int      # User default locale
LOCALE_NEUTRAL: int           # Language neutral

Dispatch Parameters

Structures for passing parameters to dispatch method invocations.

class tagDISPPARAMS:
    """Parameters for dispatch method invocation."""
    rgvarg: list         # Array of VARIANT arguments (reverse order)
    rgdispidNamedArgs: list # Array of named argument dispatch IDs
    cArgs: int          # Number of arguments
    cNamedArgs: int     # Number of named arguments

class tagEXCEPINFO:
    """Exception information for dispatch errors."""
    wCode: int          # Error code
    wReserved: int      # Reserved
    bstrSource: str     # Error source
    bstrDescription: str # Error description
    bstrHelpFile: str   # Help file path
    dwHelpContext: int  # Help context ID
    pvReserved: object  # Reserved
    pfnDeferredFillIn: object # Deferred fill function  
    scode: int          # SCODE error

Type Information

Data types and constants for working with type library information.

DISPID = int        # Type alias for dispatch identifier
SCODE = int         # Type alias for status code  
VARTYPE = int       # Type alias for variant type

# Special dispatch IDs
DISPID_UNKNOWN: int     # -1 - Unknown member
DISPID_VALUE: int       # 0 - Default member
DISPID_PROPERTYPUT: int # -3 - Property put
DISPID_NEWENUM: int     # -4 - New enumerator
DISPID_EVALUATE: int    # -5 - Evaluate
DISPID_CONSTRUCTOR: int # -6 - Constructor
DISPID_DESTRUCTOR: int  # -7 - Destructor
DISPID_COLLECT: int     # -8 - Collect

VARIANT Enumerator

Interface for enumerating collections of VARIANT values.

class IEnumVARIANT(IUnknown):
    """Enumerator for VARIANT collections."""
    
    def Next(self, count):
        """
        Get next variants from enumeration.
        
        Args:
            count (int): Maximum number of items to retrieve
        
        Returns:
            tuple: (variants_list, actual_count)
        """
    
    def Skip(self, count):
        """
        Skip specified number of variants.
        
        Args:
            count (int): Number of items to skip
        """
    
    def Reset(self):
        """Reset enumeration to beginning."""
    
    def Clone(self):
        """
        Create copy of enumerator.
        
        Returns:
            IEnumVARIANT: Cloned enumerator
        """

Currency and Decimal Types

Specialized numeric types for high-precision financial calculations.

class tagCY:
    """Currency type for exact financial calculations."""
    int64: int      # 64-bit integer scaled by 10000
    
    def __init__(self, value): ...
    def __float__(self): ...
    def __str__(self): ...

class tagDEC:
    """Decimal type for high-precision arithmetic."""
    wReserved: int      # Reserved
    scale: int          # Scale factor (0-28)
    sign: int           # Sign (0=positive, 0x80=negative)
    Hi32: int           # High 32 bits
    Lo64: int           # Low 64 bits
    
    def __init__(self, value): ...
    def __float__(self): ...
    def __str__(self): ...

Usage Examples

Basic VARIANT Operations

from comtypes.automation import VARIANT, VT_BSTR, VT_I4

# Create VARIANTs from Python values
str_var = VARIANT("Hello World")
int_var = VARIANT(42)
bool_var = VARIANT(True)

# Access values
print(str_var.value)  # "Hello World"
print(int_var.value)  # 42
print(bool_var.value) # True

# Check types
print(str_var.vt == VT_BSTR)  # True
print(int_var.vt == VT_I4)    # True

Dispatch Method Invocation

from comtypes.automation import IDispatch, INVOKE_METHOD, INVOKE_PROPERTYGET

# Assume 'obj' is an IDispatch interface
# Get dispatch ID for method name
dispids = obj.GetIDsOfNames(["SomeMethod"])
method_id = dispids[0]

# Invoke method with arguments
args = (VARIANT("arg1"), VARIANT(123))
result = obj.Invoke(method_id, 0, INVOKE_METHOD, args)

# Get property value
prop_dispids = obj.GetIDsOfNames(["SomeProperty"])
prop_value = obj.Invoke(prop_dispids[0], 0, INVOKE_PROPERTYGET, ())

Install with Tessl CLI

npx tessl i tessl/pypi-comtypes

docs

automation.md

client-api.md

core-com.md

index.md

server.md

utilities.md

tile.json