Next Previous Contents

6.6 Implementing IUnknown

Using some of the library functions used in the previous section, a generic implementation of the COM base interface IUnknown can be provided (in Haskell):

queryInterface :: Pointer Interface
               -> Pointer GUID
               -> Pointer (Pointer Interface)
               -> IO HRESULT
queryInterface iptr riid ppvObject = do
   if_ls <- getSupportedInterfaces iptr
   findInterface riid ppvObject if_ls

-- assume race conditions are resolved externally. --
addRef :: Pointer Interface -> IO Word32
addRef iptr = do
   v <- readRefCount iptr
   writeRefCount iptr (v+1)
   return v

release :: Pointer Interface -> IO Word32
release iptr = do
   v <- readRefCount iptr
   writeRefCount iptr (v-1)
   if (v-1) == 0
    then do
      releaseObj iptr
      return 0
    else do
      return (v-1)

-- library provided functions. --
getSupportedInterfaces :: Pointer Interface -> IO (StablePtr IFList)
readRefCount :: Pointer Interface -> IO Int32
writeRefCount :: Pointer Interface -> Int32 -> IO ()

The implementation of queryInterface is straightforward, fish out the interface association list that is stored as part of the interface header before calling findInterface to try to return an interface pointer at the requested interface.

The reference counting is done similarly, using information stored in the interface header to update the variable holding the reference count.


Next Previous Contents