--- win32ole.c	Sun Oct 10 03:24:07 2010
+++ win32ole.c.new	Sun Oct 10 04:55:51 2010
@@ -617,7 +617,7 @@
 static void free_enc2cp();
 static void ole_atexit();
 static int ole_set_initialized(int i);
-static LPVOID ole_get_initialized();
+static int ole_get_initialized();
 
 static HRESULT (STDMETHODCALLTYPE mf_QueryInterface)(
     IMessageFilter __RPC_FAR * This,
@@ -9155,20 +9155,27 @@
 static void
 ole_atexit()
 {
+    int* p;
     free_enc2cp();
+    p = (int*)TlsGetValue(tls_ole_initialized_key);    
+    if (p) {
+        free(p);
+    }
     TlsFree(tls_ole_initialized_key);
 }
 
 static int
 ole_set_initialized(int i)
 {
-    return TlsSetValue(tls_ole_initialized_key, (LPVOID)i);
+    int* p = (int*)TlsGetValue(tls_ole_initialized_key);
+    return *p = i;
 }
 
-static LPVOID
+static int
 ole_get_initialized()
 {
-    return TlsGetValue(tls_ole_initialized_key);
+    int* p = (int*)TlsGetValue(tls_ole_initialized_key);
+    return *p;
 }
 
 void
@@ -9414,7 +9421,6 @@
     atexit((void (*)(void))ole_atexit);
     ole_init_cp();
 
-    tls_ole_initialized_key = TlsAlloc();
     ole_initialize();
     if (CoCreateInstance(&CLSID_StdGlobalInterfaceTable, NULL,
                      CLSCTX_INPROC_SERVER, &IID_IGlobalInterfaceTable,
@@ -9427,4 +9433,19 @@
         globalInterfaceCookies = rb_ary_new();
         rb_gc_register_mark_object(globalInterfaceCookies);
     }
+}
+
+BOOL WINAPI DllMain(
+    HINSTANCE hint,
+    DWORD reason,
+    LPVOID reserved
+    )
+{
+    if (reason == DLL_PROCESS_ATTACH) {
+        tls_ole_initialized_key = TlsAlloc();
+    }
+    if (reason == DLL_THREAD_ATTACH || reason == DLL_PROCESS_ATTACH) {
+        TlsSetValue(tls_ole_initialized_key, calloc(1, sizeof(int)));
+    }
+    return TRUE;
 }

