CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-net-java-dev-jna--jna-platform

Java Native Access Platform provides cross-platform mappings and utilities for commonly used platform functions across Windows, macOS, and Linux systems.

Pending
Overview
Eval results
Files

com.mddocs/

COM Automation (Windows)

Complete Component Object Model (COM) support for Windows automation, including base interfaces, utility classes, type library importing, and comprehensive annotation-based programming model. COM enables interaction with Windows applications, system services, and automation objects.

Capabilities

Base COM Interfaces

Core COM interfaces that form the foundation of all COM objects and automation.

/**
 * Base COM interface - all COM objects implement IUnknown
 */
public interface IUnknown {
    /**
     * Query for a different interface on the object
     * @param riid Interface identifier to query for
     * @param ppvObject Output pointer to interface
     * @return HRESULT status code
     */
    HRESULT QueryInterface(REFIID riid, PointerByReference ppvObject);
    
    /**
     * Increment object reference count
     * @return New reference count
     */
    int AddRef();
    
    /**
     * Decrement object reference count, destroy when reaches zero
     * @return New reference count (0 means object was destroyed)
     */
    int Release();
}

/**
 * Automation interface extending IUnknown for scripting and late binding
 */
public interface IDispatch extends IUnknown {
    /**
     * Get number of type info interfaces
     * @param pctinfo Output count of type info interfaces
     * @return HRESULT status code
     */
    HRESULT GetTypeInfoCount(IntByReference pctinfo);
    
    /**
     * Get type information for object
     * @param iTInfo Type info index (usually 0)
     * @param lcid Locale identifier
     * @param ppTInfo Output type information
     * @return HRESULT status code
     */
    HRESULT GetTypeInfo(int iTInfo, LCID lcid, PointerByReference ppTInfo);
    
    /**
     * Get dispatch IDs for names
     * @param riid Reserved (should be IID_NULL)
     * @param rgszNames Array of names to get IDs for
     * @param cNames Number of names
     * @param lcid Locale identifier
     * @param rgDispId Output array of dispatch IDs
     * @return HRESULT status code
     */
    HRESULT GetIDsOfNames(REFIID riid, String[] rgszNames, int cNames, 
                         LCID lcid, DISPIDByReference rgDispId);
    
    /**
     * Invoke method or access property
     * @param dispIdMember Dispatch ID of member
     * @param riid Reserved (should be IID_NULL)
     * @param lcid Locale identifier
     * @param wFlags Invoke flags (method, property get/put)
     * @param pDispParams Parameters for invocation
     * @param pVarResult Return value
     * @param pExcepInfo Exception information
     * @param puArgErr Argument error index
     * @return HRESULT status code
     */
    HRESULT Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags,
                   DISPPARAMS.ByReference pDispParams, VARIANT.ByReference pVarResult,
                   EXCEPINFO.ByReference pExcepInfo, IntByReference puArgErr);
}

Connection Points and Events

COM interfaces for event handling and callback mechanisms.

/**
 * Connection point interface for COM events
 */
public interface IConnectionPoint extends IUnknown {
    /**
     * Get interface ID for this connection point
     * @param pIID Output interface identifier
     * @return HRESULT status code
     */
    HRESULT GetConnectionInterface(Pointer pIID);
    
    /**
     * Get connection point container
     * @param ppCPC Output connection point container
     * @return HRESULT status code
     */
    HRESULT GetConnectionPointContainer(PointerByReference ppCPC);
    
    /**
     * Establish connection to event sink
     * @param pUnkSink Event sink interface
     * @param pdwCookie Output connection cookie
     * @return HRESULT status code
     */
    HRESULT Advise(IUnknown pUnkSink, DWORDByReference pdwCookie);
    
    /**
     * Terminate connection
     * @param dwCookie Connection cookie from Advise
     * @return HRESULT status code
     */
    HRESULT Unadvise(DWORD dwCookie);
    
    /**
     * Enumerate existing connections
     * @param ppEnum Output enumerator for connections
     * @return HRESULT status code
     */
    HRESULT EnumConnections(PointerByReference ppEnum);
}

/**
 * Connection point container interface
 */
public interface IConnectionPointContainer extends IUnknown {
    /**
     * Enumerate all connection points
     * @param ppEnum Output enumerator for connection points
     * @return HRESULT status code
     */
    HRESULT EnumConnectionPoints(PointerByReference ppEnum);
    
    /**
     * Find connection point for specific interface
     * @param riid Interface identifier to find
     * @param ppCP Output connection point
     * @return HRESULT status code
     */
    HRESULT FindConnectionPoint(REFIID riid, PointerByReference ppCP);
}

Object Persistence

COM interfaces for object serialization and persistence.

/**
 * Base persistence interface
 */
public interface IPersist extends IUnknown {
    /**
     * Get class identifier for persistent object
     * @param pClassID Output class identifier
     * @return HRESULT status code
     */
    HRESULT GetClassID(Pointer pClassID);
}

/**
 * Stream-based persistence
 */
public interface IPersistStream extends IPersist {
    /**
     * Check if object is dirty (needs saving)
     * @return S_OK if dirty, S_FALSE if clean
     */
    HRESULT IsDirty();
    
    /**
     * Load object from stream
     * @param pStm Input stream
     * @return HRESULT status code
     */
    HRESULT Load(Pointer pStm);
    
    /**
     * Save object to stream
     * @param pStm Output stream
     * @param fClearDirty Whether to clear dirty flag
     * @return HRESULT status code
     */
    HRESULT Save(Pointer pStm, boolean fClearDirty);
    
    /**
     * Get size needed to save object
     * @param pcbSize Output size in bytes
     * @return HRESULT status code
     */
    HRESULT GetSizeMax(Pointer pcbSize);
}

COM Object Creation and Management

High-level utilities for creating and managing COM objects with automatic lifecycle management.

/**
 * COM object factory for creating and managing COM instances
 */
public class Factory {
    /**
     * Create COM object from program ID
     * @param progid Program identifier (e.g., "Excel.Application")
     * @return COM object wrapper
     * @throws COMException if creation fails
     */
    public static IDispatch createObject(String progid) throws COMException;
    
    /**
     * Get active COM object by program ID
     * @param progid Program identifier
     * @return Existing COM object wrapper
     * @throws COMException if object not found or retrieval fails
     */
    public static IDispatch getActiveObject(String progid) throws COMException;
    
    /**
     * Create COM object from class ID
     * @param clsid Class identifier
     * @return COM object wrapper
     * @throws COMException if creation fails
     */
    public static IUnknown createObject(CLSID clsid) throws COMException;
}

/**
 * Enhanced object factory with additional features
 */
public class ObjectFactory {
    /**
     * Create COM object with specific interface
     * @param progid Program identifier
     * @param interfaceClass Interface class to return
     * @return Typed COM object wrapper
     * @throws COMException if creation fails
     */
    public static <T> T createObject(String progid, Class<T> interfaceClass) throws COMException;
    
    /**
     * Create COM object with connection point support
     * @param progid Program identifier
     * @param eventSink Event handler implementation
     * @return COM object wrapper with event connection
     * @throws COMException if creation fails
     */
    public static IDispatch createObjectWithEvents(String progid, Object eventSink) throws COMException;
    
    /**
     * Release COM object and clean up resources
     * @param comObject COM object to release
     */
    public static void releaseObject(Object comObject);
}

Dynamic Proxy Support

Dynamic proxy implementation for type-safe COM automation without type libraries.

/**
 * Dynamic proxy for COM objects providing type-safe access
 */
public class ProxyObject implements InvocationHandler {
    /**
     * Create proxy for COM object
     * @param comObject Underlying COM object
     * @param interfaceClass Interface to implement
     * @return Proxy implementing the interface
     */
    public static <T> T createProxy(IDispatch comObject, Class<T> interfaceClass);
    
    /**
     * Get underlying COM object from proxy
     * @param proxy Proxy object
     * @return Underlying IDispatch interface
     */
    public static IDispatch getComObject(Object proxy);
    
    /**
     * Handle method invocation on proxy
     * @param proxy Proxy instance
     * @param method Method being invoked
     * @param args Method arguments
     * @return Method result
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
}

COM Threading Support

Utilities for managing COM objects across different threading models.

/**
 * COM threading utilities for apartment and free threading
 */
public class ComThread {
    /**
     * Initialize COM on current thread
     * @param threadingModel Threading model (COINIT_APARTMENTTHREADED, etc.)
     * @throws COMException if initialization fails
     */
    public static void initMTA(int threadingModel) throws COMException;
    
    /**
     * Initialize COM with Single Threaded Apartment
     * @throws COMException if initialization fails
     */
    public static void initSTA() throws COMException;
    
    /**
     * Initialize COM with Multi Threaded Apartment
     * @throws COMException if initialization fails
     */
    public static void initMTA() throws COMException;
    
    /**
     * Uninitialize COM on current thread
     */
    public static void uninitialize();
    
    /**
     * Execute operation in COM apartment thread
     * @param operation Operation to execute
     * @return Operation result
     * @throws Exception if operation fails
     */
    public static <T> T executeInComThread(Callable<T> operation) throws Exception;
}

Event Handling Support

Simplified event handling for COM automation objects.

/**
 * Callback proxy for COM event handling
 */
public class CallbackProxy implements InvocationHandler {
    /**
     * Create event sink proxy
     * @param eventHandler Event handler object
     * @param sinkInterface Event sink interface
     * @return Proxy implementing sink interface
     */
    public static Object createProxy(Object eventHandler, Class<?> sinkInterface);
    
    /**
     * Connect event handler to COM object
     * @param comObject COM object that fires events
     * @param eventHandler Handler object with event methods
     * @param sinkInterface Event sink interface
     * @return Connection cookie for later disconnection
     * @throws COMException if connection fails
     */
    public static int connectEvents(IDispatch comObject, Object eventHandler, 
                                   Class<?> sinkInterface) throws COMException;
    
    /**
     * Disconnect event handler from COM object
     * @param comObject COM object
     * @param connectionCookie Cookie from connectEvents
     * @throws COMException if disconnection fails
     */
    public static void disconnectEvents(IDispatch comObject, int connectionCookie) throws COMException;
}

Type Library Import

Tools for importing COM type libraries and generating Java bindings.

/**
 * Type library importer for generating Java bindings from COM type libraries
 */
public class TlbImp {
    /**
     * Generate Java bindings from type library file
     * @param tlbFile Type library file path
     * @param outputPackage Output Java package name
     * @param outputDir Output directory for generated files
     * @throws Exception if import fails
     */
    public static void generateBindings(String tlbFile, String outputPackage, 
                                       String outputDir) throws Exception;
    
    /**
     * Generate bindings from program ID
     * @param progid Program identifier to import
     * @param outputPackage Output Java package name
     * @param outputDir Output directory
     * @throws Exception if import fails
     */
    public static void generateBindingsFromProgId(String progid, String outputPackage, 
                                                 String outputDir) throws Exception;
    
    /**
     * List available type libraries on system
     * @return Array of type library information
     */
    public static TypeLibInfo[] getInstalledTypeLibraries();
}

/**
 * Type library information
 */
public class TypeLibInfo {
    public String getName();
    public String getVersion();
    public String getPath();
    public GUID getGuid();
}

COM Annotations

Annotations for declarative COM programming and automatic proxy generation.

/**
 * Mark interface as COM interface
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ComInterface {
    /**
     * Interface identifier (optional)
     */
    String iid() default "";
}

/**
 * Mark class as COM object
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ComObject {
    /**
     * Program identifier
     */
    String progid();
    
    /**
     * Class identifier (optional)
     */
    String clsid() default "";
}

/**
 * Mark method as COM method
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ComMethod {
    /**
     * Dispatch ID (optional for late binding)
     */
    int dispId() default -1;
    
    /**
     * Method name (defaults to Java method name)
     */
    String name() default "";
}

/**
 * Mark method as COM property
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ComProperty {
    /**
     * Dispatch ID
     */
    int dispId();
    
    /**
     * Property access type
     */
    PropertyAccess access() default PropertyAccess.GET;
}

/**
 * Mark method as COM event callback
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ComEventCallback {
    /**
     * Dispatch ID for event
     */
    int dispId();
}

/**
 * Property access enumeration
 */
public enum PropertyAccess {
    GET, PUT, PUT_REF
}

COM Utility Classes

Essential utility classes that simplify COM programming and handle complex operations like error checking, type library access, and object management.

COMUtils - Core Utilities

Helper functions for COM operations, error handling, and system COM registry access.

/**
 * Core COM utility functions for error handling and system information
 */
public class COMUtils {
    /**
     * Check if HRESULT indicates success
     * @param hr HRESULT value to check
     * @return true if successful
     */
    public static boolean SUCCEEDED(HRESULT hr);
    
    /**
     * Check if HRESULT indicates failure
     * @param hr HRESULT value to check
     * @return true if failed
     */
    public static boolean FAILED(HRESULT hr);
    
    /**
     * Check HRESULT and throw exception if failed
     * @param hr HRESULT value to check
     * @throws COMException if hr indicates failure
     */
    public static void checkRC(HRESULT hr);
    
    /**
     * Check HRESULT with detailed error information
     * @param hr HRESULT value to check
     * @param pExcepInfo Exception information structure
     * @param puArgErr Argument error reference
     * @throws COMException if hr indicates failure with detailed error info
     */
    public static void checkRC(HRESULT hr, EXCEPINFO pExcepInfo, IntByReference puArgErr);
    
    /**
     * Check if COM is initialized on current thread
     * @return true if COM is initialized
     */
    public static boolean comIsInitialized();
    
    /**
     * Get information about all registered COM objects on the system
     * @return List of COMInfo objects describing registered COM classes
     */
    public static ArrayList<COMInfo> getAllCOMInfoOnSystem();
}

/**
 * Information about a registered COM object
 */
public static class COMInfo {
    public String clsid;         // Class ID
    public String progid;        // Programmatic ID
    public String typelib;       // Type library ID
    public String inprocServer32; // In-process server path
    public String localServer32;  // Local server path
}

TypeLibUtil - Type Library Access

High-level wrapper for accessing COM type library information and metadata.

/**
 * Type library access and manipulation utilities
 */
public class TypeLibUtil {
    /**
     * Load type library by CLSID and version
     * @param clsidStr Type library CLSID as string
     * @param wVerMajor Major version number
     * @param wVerMinor Minor version number
     */
    public TypeLibUtil(String clsidStr, int wVerMajor, int wVerMinor);
    
    /**
     * Load type library from file
     * @param file Path to type library file (.tlb, .dll, .exe)
     */
    public TypeLibUtil(String file);
    
    /**
     * Get number of type definitions in library
     * @return Count of type definitions
     */
    public int getTypeInfoCount();
    
    /**
     * Get type kind for type info at index
     * @param index Index of type info
     * @return TYPEKIND indicating type (interface, coclass, enum, etc.)
     */
    public TYPEKIND getTypeInfoType(int index);
    
    /**
     * Get type information object at index
     * @param index Index of type info
     * @return ITypeInfo interface for type
     */
    public ITypeInfo getTypeInfo(int index);
    
    /**
     * Get type info utility wrapper at index
     * @param index Index of type info
     * @return TypeInfoUtil wrapper for convenient access
     */
    public TypeInfoUtil getTypeInfoUtil(int index);
    
    /**
     * Get type library attributes
     * @return TLIBATTR structure with library metadata
     */
    public TLIBATTR getLibAttr();
    
    /**
     * Get documentation for type at index
     * @param index Index of type (-1 for library documentation)
     * @return TypeLibDoc with name, help text, and help context
     */
    public TypeLibDoc getDocumentation(int index);
}

TypeInfoUtil - Type Information Access

Wrapper for ITypeInfo providing convenient access to type metadata, function descriptors, and member information.

/**
 * Type information access and manipulation utilities
 */
public class TypeInfoUtil {
    /**
     * Get type attributes
     * @return TYPEATTR structure with type metadata
     */
    public TYPEATTR getTypeAttr();
    
    /**
     * Get function descriptor for method at index
     * @param index Function index
     * @return FUNCDESC structure with function metadata
     */
    public FUNCDESC getFuncDesc(int index);
    
    /**
     * Get variable descriptor for property/field at index
     * @param index Variable index
     * @return VARDESC structure with variable metadata
     */
    public VARDESC getVarDesc(int index);
    
    /**
     * Get names for member ID
     * @param memid Member ID
     * @param maxNames Maximum number of names to retrieve
     * @return Array of names (first is member name, rest are parameter names)
     */
    public String[] getNames(MEMBERID memid, int maxNames);
    
    /**
     * Get reference type for implemented interface at index
     * @param index Implementation index
     * @return HREFTYPE for referenced interface
     */
    public HREFTYPE getRefTypeOfImplType(int index);
    
    /**
     * Get implementation flags for interface at index
     * @param index Implementation index
     * @return Implementation flags (default, source, etc.)
     */
    public int getImplTypeFlags(int index);
    
    /**
     * Invoke method or property on instance
     * @param pvInstance Object instance
     * @param memid Member ID to invoke
     * @param wFlags Invocation flags (method, property get/put)
     * @param pDispParams Parameters for invocation
     * @return Invoke result with return value and parameter results
     */
    public Invoke Invoke(PVOID pvInstance, MEMBERID memid, WORD wFlags, 
                        DISPPARAMS.ByReference pDispParams);
}

COM Object Base Classes

Foundation classes for building COM object wrappers with lifecycle management.

/**
 * Base class for COM object wrappers
 */
public abstract class COMBindingBaseObject {
    /**
     * Create COM object wrapper by CLSID
     * @param clsid Class ID of COM object
     * @param useActiveInstance true to connect to existing instance
     */
    protected COMBindingBaseObject(CLSID clsid, boolean useActiveInstance);
    
    /**
     * Create COM object wrapper by Program ID
     * @param progId Programmatic ID of COM object
     * @param useActiveInstance true to connect to existing instance
     */
    protected COMBindingBaseObject(String progId, boolean useActiveInstance);
    
    /**
     * Get IDispatch interface for automation
     * @return IDispatch interface
     */
    public IDispatch getIDispatch();
    
    /**
     * Get IUnknown interface
     * @return IUnknown interface
     */
    public IUnknown getIUnknown();
    
    /**
     * Invoke OLE automation method
     * @param nType Invocation type (method, property get/put)
     * @param pvResult Reference for return value
     * @param name Method or property name
     * @param pArgs Method arguments
     * @return HRESULT from invocation
     */
    protected HRESULT oleMethod(int nType, VARIANT.ByReference pvResult, 
                               String name, VARIANT[] pArgs);
}

/**
 * Late binding COM object wrapper with convenience methods
 */
public abstract class COMLateBindingObject extends COMBindingBaseObject {
    /**
     * Get property value as IDispatch
     * @param propertyName Property name
     * @return Property value as IDispatch
     */
    protected IDispatch getAutomationProperty(String propertyName);
    
    /**
     * Get boolean property value
     * @param propertyName Property name
     * @return Property value as boolean
     */
    protected boolean getBooleanProperty(String propertyName);
    
    /**
     * Get date property value
     * @param propertyName Property name
     * @return Property value as Date
     */
    protected Date getDateProperty(String propertyName);
    
    /**
     * Get integer property value
     * @param propertyName Property name
     * @return Property value as int
     */
    protected int getIntProperty(String propertyName);
    
    /**
     * Get string property value
     * @param propertyName Property name
     * @return Property value as String
     */
    protected String getStringProperty(String propertyName);
    
    /**
     * Invoke method with no parameters
     * @param methodName Method name
     * @return Method result as VARIANT
     */
    protected VARIANT invoke(String methodName);
    
    /**
     * Invoke method with parameters
     * @param methodName Method name
     * @param args Method arguments
     * @return Method result as VARIANT
     */
    protected VARIANT invoke(String methodName, VARIANT[] args);
    
    /**
     * Set property value (multiple overloads for different types)
     * @param propertyName Property name
     * @param value Property value (boolean, Date, int, String)
     */
    protected void setProperty(String propertyName, boolean value);
    protected void setProperty(String propertyName, Date value);
    protected void setProperty(String propertyName, int value);
    protected void setProperty(String propertyName, String value);
}

COM Threading Management

Thread-safe COM object creation and execution with automatic apartment management.

/**
 * COM thread management for apartment threading
 */
public class ComThread {
    /**
     * Create COM thread with timeout and error handling
     * @param threadName Thread name for debugging
     * @param timeoutMilliseconds Operation timeout
     * @param uncaughtExceptionHandler Exception handler
     */
    public ComThread(String threadName, long timeoutMilliseconds, 
                    UncaughtExceptionHandler uncaughtExceptionHandler);
    
    /**
     * Execute callable task in COM apartment thread
     * @param task Task to execute
     * @return Task result
     */
    public <T> T execute(Callable<T> task);
    
    /**
     * Terminate COM thread and clean up resources
     * @param timeoutMilliseconds Termination timeout
     */
    public void terminate(long timeoutMilliseconds);
}

/**
 * Enhanced object factory with COM threading support
 */
public class Factory extends ObjectFactory {
    /**
     * Get associated COM thread for this factory
     * @return ComThread instance managing COM operations
     */
    public ComThread getComThread();
    
    // All ObjectFactory methods are automatically executed in proper COM thread context
}

Complete COM Usage Examples

Basic COM Automation:

import com.sun.jna.platform.win32.COM.util.*;

// Create Excel application
IDispatch excel = Factory.createObject("Excel.Application");

// Make Excel visible
excel.setProperty("Visible", true);

// Create new workbook
IDispatch workbooks = (IDispatch) excel.getProperty("Workbooks");
IDispatch workbook = (IDispatch) workbooks.invoke("Add");

// Get first worksheet
IDispatch worksheets = (IDispatch) workbook.getProperty("Worksheets");
IDispatch worksheet = (IDispatch) worksheets.invoke("Item", 1);

// Set cell value
IDispatch range = (IDispatch) worksheet.invoke("Range", "A1");
range.setProperty("Value", "Hello from JNA!");

// Save and close
workbook.invoke("SaveAs", "C:\\temp\\test.xlsx");
workbook.invoke("Close");
excel.invoke("Quit");

// Clean up
ObjectFactory.releaseObject(excel);

Event Handling:

// Event handler class
public class ExcelEventHandler {
    @ComEventCallback(dispId = 1565) // WorkbookOpen event
    public void onWorkbookOpen(IDispatch workbook) {
        System.out.println("Workbook opened: " + workbook.getProperty("Name"));
    }
    
    @ComEventCallback(dispId = 1558) // WorkbookBeforeClose event  
    public void onWorkbookBeforeClose(IDispatch workbook, BooleanByReference cancel) {
        System.out.println("Workbook closing: " + workbook.getProperty("Name"));
        // Set cancel.setValue(true) to prevent closing
    }
}

// Connect events
ExcelEventHandler handler = new ExcelEventHandler();
IDispatch excel = Factory.createObject("Excel.Application");

int connectionCookie = CallbackProxy.connectEvents(excel, handler, 
    ExcelEventHandler.class);

// Use Excel with event handling...

// Disconnect events when done
CallbackProxy.disconnectEvents(excel, connectionCookie);
ObjectFactory.releaseObject(excel);

Annotation-Based COM Programming:

@ComInterface(iid = "{00020970-0000-0000-C000-000000000046}")
public interface IApplication {
    @ComProperty(dispId = 558)
    boolean getVisible();
    
    @ComProperty(dispId = 558, access = PropertyAccess.PUT)
    void setVisible(boolean visible);
    
    @ComMethod(dispId = 302)
    IWorkbooks getWorkbooks();
    
    @ComMethod(dispId = 1105)  
    void quit();
}

// Use with proxy
IDispatch excelDispatch = Factory.createObject("Excel.Application");
IApplication excel = ProxyObject.createProxy(excelDispatch, IApplication.class);

excel.setVisible(true);
IWorkbooks workbooks = excel.getWorkbooks();
// ... use type-safe interface
excel.quit();

Install with Tessl CLI

npx tessl i tessl/maven-net-java-dev-jna--jna-platform

docs

com.md

cross-platform.md

drag-drop.md

index.md

mac.md

unix-linux.md

windows.md

tile.json