Source

pypy / pypy / module / test_lib_pypy / ctypes_tests / test_commethods.py

# unittest for SOME ctypes com function calls.
# Can't resist from implementing some kind of mini-comtypes
# theller ;-)

import py
import sys
if sys.platform != "win32":
    py.test.skip('windows only test')

import ctypes, new, unittest
from ctypes.wintypes import HRESULT
from _ctypes import COMError

oleaut32 = ctypes.OleDLL("oleaut32")

class UnboundMethod(object):
    def __init__(self, func, index, name):
        self.func = func
        self.index = index
        self.name = name
        self.__doc__ = func.__doc__

    def __repr__(self):
        return "<Unbound COM method index %d: %s at %x>" % (self.index, self.name, id(self))

    def __get__(self, instance, owner):
        if instance is None:
            return self
        return new.instancemethod(self.func, instance, owner)
    
def commethod(index, restype, *argtypes):
    """A decorator that generates COM methods.  The decorated function
    itself is not used except for it's name."""
    def make_commethod(func):
        comfunc = ctypes.WINFUNCTYPE(restype, *argtypes)(index, func.__name__)
        comfunc.__name__ = func.__name__
        comfunc.__doc__ = func.__doc__
        return UnboundMethod(comfunc, index, func.__name__)
    return make_commethod

class ICreateTypeLib2(ctypes.c_void_p):

    @commethod(1, ctypes.c_long)
    def AddRef(self):
        pass

    @commethod(2, ctypes.c_long)
    def Release(self):
        pass

    @commethod(4, HRESULT, ctypes.c_wchar_p)
    def SetName(self):
        """Set the name of the library."""

    @commethod(12, HRESULT)
    def SaveAllChanges(self):
        pass


CreateTypeLib2 = oleaut32.CreateTypeLib2
CreateTypeLib2.argtypes = (ctypes.c_int, ctypes.c_wchar_p, ctypes.POINTER(ICreateTypeLib2))

################################################################

def test_basic_comtypes():
    punk = ICreateTypeLib2()
    hr = CreateTypeLib2(0, "foobar.tlb", punk)
    assert hr == 0

    assert 2 == punk.AddRef()
    assert 3 == punk.AddRef()
    assert 4 == punk.AddRef()

    punk.SetName("TypeLib_ByPYPY")
    py.test.raises(COMError, lambda: punk.SetName(None))

    # This would save the typelib to disk.
    ## punk.SaveAllChanges()

    assert 3 == punk.Release()
    assert 2 == punk.Release()
    assert 1 == punk.Release()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.