From 5936b3c5b803efe337616d642cbce4bc194bd872 Mon Sep 17 00:00:00 2001 From: Tony Roberts Date: Wed, 26 Aug 2026 16:55:36 +0100 Subject: [PATCH] Clear Variant in DispatchComMethod.invoke before returning The returned Variant can contain an IDispatch/IUnknown, and leaving that to be cleared by the GC sometime later can cause issues if that doesn't happen on the correct thread. Unlike COM wrapper objects, the Variant's finalizer doesn't schedule the actual clearing on the COM thread. Instead clearing just happens whenever the object is finalized, which can be on the wrong thread. The invoke method is already running on the correct COM thread and so the safest fix is to simply clear the variant before returning. Fixes #91 --- runtime/src/main/java/com4j/DispatchComMethod.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/runtime/src/main/java/com4j/DispatchComMethod.java b/runtime/src/main/java/com4j/DispatchComMethod.java index 9ea7029a..c6462a51 100644 --- a/runtime/src/main/java/com4j/DispatchComMethod.java +++ b/runtime/src/main/java/com4j/DispatchComMethod.java @@ -47,10 +47,14 @@ Object invoke(long ptr, Object[] args) { if(v==null) return null; - if(retType==void.class) - return null; + try { + if(retType==void.class) + return null; - return v.convertTo(retType); + return v.convertTo(retType); + } finally { + v.clear(); + } } private static final int DISPATCH_METHOD = 0x1;