ctypes-commit Mailing List for ctypes (Page 36)
Brought to you by:
theller
You can subscribe to this list here.
2004 |
Jan
|
Feb
|
Mar
|
Apr
(8) |
May
(90) |
Jun
(143) |
Jul
(106) |
Aug
(94) |
Sep
(84) |
Oct
(163) |
Nov
(60) |
Dec
(58) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2005 |
Jan
(128) |
Feb
(79) |
Mar
(227) |
Apr
(192) |
May
(179) |
Jun
(41) |
Jul
(53) |
Aug
(103) |
Sep
(28) |
Oct
(38) |
Nov
(81) |
Dec
(17) |
2006 |
Jan
(184) |
Feb
(111) |
Mar
(188) |
Apr
(67) |
May
(58) |
Jun
(123) |
Jul
(73) |
Aug
|
Sep
|
Oct
(1) |
Nov
|
Dec
|
From: Thomas H. <th...@us...> - 2005-11-08 20:34:33
|
Update of /cvsroot/ctypes/ctypes/source In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24908 Modified Files: Tag: branch_1_0 _ctypes.c Log Message: Label as __version__ = "0.9.9.0". Index: _ctypes.c =================================================================== RCS file: /cvsroot/ctypes/ctypes/source/_ctypes.c,v retrieving revision 1.226.2.35 retrieving revision 1.226.2.36 diff -C2 -d -r1.226.2.35 -r1.226.2.36 *** _ctypes.c 3 Nov 2005 20:04:12 -0000 1.226.2.35 --- _ctypes.c 8 Nov 2005 20:34:23 -0000 1.226.2.36 *************** *** 4333,4337 **** PyModule_AddObject(m, "FUNCFLAG_CDECL", PyInt_FromLong(FUNCFLAG_CDECL)); PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyInt_FromLong(FUNCFLAG_PYTHONAPI)); ! PyModule_AddStringConstant(m, "__version__", "0.9.8"); #ifdef RTLD_LOCAL --- 4333,4337 ---- PyModule_AddObject(m, "FUNCFLAG_CDECL", PyInt_FromLong(FUNCFLAG_CDECL)); PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyInt_FromLong(FUNCFLAG_PYTHONAPI)); ! PyModule_AddStringConstant(m, "__version__", "0.9.9.0"); #ifdef RTLD_LOCAL |
From: Thomas H. <th...@us...> - 2005-11-08 20:34:21
|
Update of /cvsroot/ctypes/ctypes In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24866 Modified Files: Tag: branch_1_0 setup.py Log Message: Label as __version__ = "0.9.9.0". Index: setup.py =================================================================== RCS file: /cvsroot/ctypes/ctypes/setup.py,v retrieving revision 1.122.2.7 retrieving revision 1.122.2.8 diff -C2 -d -r1.122.2.7 -r1.122.2.8 *** setup.py 4 Nov 2005 08:07:21 -0000 1.122.2.7 --- setup.py 8 Nov 2005 20:34:13 -0000 1.122.2.8 *************** *** 12,16 **** LIBFFI_SOURCES='source/gcc/libffi' ! __version__ = "0.9.8" ################################################################ --- 12,16 ---- LIBFFI_SOURCES='source/gcc/libffi' ! __version__ = "0.9.9.0" ################################################################ |
From: Thomas H. <th...@us...> - 2005-11-08 20:33:56
|
Update of /cvsroot/ctypes/ctypes/comtypes In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24702 Modified Files: Tag: branch_1_0 __init__.py Log Message: Label as __version__ = "0.1.1". Check ctypes __version__ - requires "0.9.9.0". Small cleanups. Index: __init__.py =================================================================== RCS file: /cvsroot/ctypes/ctypes/comtypes/__init__.py,v retrieving revision 1.25.2.34 retrieving revision 1.25.2.35 diff -C2 -d -r1.25.2.34 -r1.25.2.35 *** __init__.py 20 Oct 2005 17:24:53 -0000 1.25.2.34 --- __init__.py 8 Nov 2005 20:33:18 -0000 1.25.2.35 *************** *** 1,14 **** ! # requires ctypes 0.9.8 or later import new ##import warnings import types import sys ! try: ! set ! except NameError: ! from sets import Set as set from ctypes import * from _ctypes import COMError import logging logger = logging.getLogger("comtypes") --- 1,19 ---- ! # requires ctypes 0.9.9.0 or later import new ##import warnings import types import sys ! from ctypes import * + from ctypes import __version__ as _ctypes_version from _ctypes import COMError + __version__ = "0.1.1" + + _ctypes_required = "0.9.9.0" + + if _ctypes_version.split(".") < _ctypes_required.split("."): + raise ImportError("requires ctypes %s or later, not %s" % (_ctypes_required, _ctypes_version)) + import logging logger = logging.getLogger("comtypes") *************** *** 154,158 **** # Accept an CoClass instance which exposes the interface required. try: ! table = getattr(value, "_com_pointers_") except AttributeError: pass --- 159,163 ---- # Accept an CoClass instance which exposes the interface required. try: ! table = value._com_pointers_ except AttributeError: pass *************** *** 254,264 **** def _disp_property(self, memid, idlflags): # XXX doc string missing in property ! def get(obj): return obj.Invoke(memid, _invkind=2) # DISPATCH_PROPERTYGET if "readonly" in idlflags: return property(get) ! def set(obj, value): return obj.Invoke(memid, value, _invkind=4) # DISPATCH_PROPERTYPUT ! return property(get, set) def __get_baseinterface_methodcount(self): --- 259,269 ---- def _disp_property(self, memid, idlflags): # XXX doc string missing in property ! def _get(obj): return obj.Invoke(memid, _invkind=2) # DISPATCH_PROPERTYGET if "readonly" in idlflags: return property(get) ! def _set(obj, value): return obj.Invoke(memid, value, _invkind=4) # DISPATCH_PROPERTYPUT ! return property(_get, _set) def __get_baseinterface_methodcount(self): |
From: Thomas H. <th...@us...> - 2005-11-08 20:26:22
|
Update of /cvsroot/ctypes/ctypes In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23165 Modified Files: Tag: branch_1_0 setup_comtypes.py Log Message: Get comtypes __version__ from comtypes itself. Index: setup_comtypes.py =================================================================== RCS file: /cvsroot/ctypes/ctypes/Attic/setup_comtypes.py,v retrieving revision 1.1.2.1 retrieving revision 1.1.2.2 diff -C2 -d -r1.1.2.1 -r1.1.2.2 *** setup_comtypes.py 24 Aug 2005 12:38:16 -0000 1.1.2.1 --- setup_comtypes.py 8 Nov 2005 20:26:08 -0000 1.1.2.2 *************** *** 10,16 **** ----------------------------------------------------------------""" ! ##from distutils.core import setup ! from setuptools import setup ! ##import comtypes.client classifiers = [ --- 10,16 ---- ----------------------------------------------------------------""" ! from distutils.core import setup ! ! import comtypes classifiers = [ *************** *** 35,41 **** classifiers=classifiers, ! version="1.0", packages=["comtypes", "comtypes.client", "comtypes.tools", ! "comtypes.unittests"]) --- 35,41 ---- classifiers=classifiers, ! version=comtypes.__version__, packages=["comtypes", "comtypes.client", "comtypes.tools", ! "comtypes.test"]) |
From: Bradley L S. <bs...@us...> - 2005-11-08 01:14:11
|
Update of /cvsroot/ctypes/ctypes-java/src/jni In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24044/src/jni Modified Files: javactypes.h module.c CFunction.c CCallbackFunction.c Log Message: Index: CCallbackFunction.c =================================================================== RCS file: /cvsroot/ctypes/ctypes-java/src/jni/CCallbackFunction.c,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** CCallbackFunction.c 29 Aug 2004 01:30:03 -0000 1.6 --- CCallbackFunction.c 8 Nov 2005 01:14:00 -0000 1.7 *************** *** 240,243 **** --- 240,244 ---- } else if (IsSubclassOf(env, obj, Class_CPointer)) { int value; + long l; jmethodID cid = (*env)->GetMethodID(env, obj, "<init>", "(J)V"); if (cid == NULL) { *************** *** 245,250 **** } //value = *((int*)*pArgs); ! value = (int)*pArgs; ! arg = (*env)->NewObject(env, obj, cid, (long) value); pArgs += 1; } --- 246,253 ---- } //value = *((int*)*pArgs); ! value = (int)pArgs; ! l = (long) value; ! //value = (int) **pArgs; ! arg = (*env)->NewObject(env, obj, cid, value); pArgs += 1; } Index: module.c =================================================================== RCS file: /cvsroot/ctypes/ctypes-java/src/jni/module.c,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** module.c 29 Aug 2004 01:30:03 -0000 1.5 --- module.c 8 Nov 2005 01:14:00 -0000 1.6 *************** *** 36,39 **** --- 36,40 ---- jclass Class_CShort; jclass Class_CLong; + jclass Class_CULong; jclass Class_CLongLong; jclass Class_CFloat; *************** *** 110,113 **** --- 111,123 ---- } + cls = (*env)->FindClass(env, "ctypes/java/CULong"); + if (cls == NULL) { + return JNI_ERR; + } + Class_CULong = (*env)->NewGlobalRef(env, cls); + if (Class_CULong == NULL) { + return JNI_ERR; + } + cls = (*env)->FindClass(env, "ctypes/java/CLongLong"); if (cls == NULL) { Index: javactypes.h =================================================================== RCS file: /cvsroot/ctypes/ctypes-java/src/jni/javactypes.h,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** javactypes.h 21 Mar 2004 23:43:35 -0000 1.4 --- javactypes.h 8 Nov 2005 01:14:00 -0000 1.5 *************** *** 36,39 **** --- 36,40 ---- extern jclass Class_CShort; extern jclass Class_CLong; + extern jclass Class_CULong; extern jclass Class_CLongLong; extern jclass Class_CFloat; Index: CFunction.c =================================================================== RCS file: /cvsroot/ctypes/ctypes-java/src/jni/CFunction.c,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** CFunction.c 29 Aug 2004 01:30:03 -0000 1.7 --- CFunction.c 8 Nov 2005 01:14:00 -0000 1.8 *************** *** 272,276 **** if ((*env)->IsInstanceOf(env, obj, Class_CLong)) { parm->tag = 'l'; ! mid = (*env)->GetMethodID(env, Class_CLong, "longValue", "()J"); parm->value.l = (*env)->CallLongMethod(env, obj, mid); parm->obj = obj; --- 272,284 ---- if ((*env)->IsInstanceOf(env, obj, Class_CLong)) { parm->tag = 'l'; ! mid = (*env)->GetMethodID(env, Class_CLong, "getValue", "()J"); ! parm->value.l = (*env)->CallLongMethod(env, obj, mid); ! parm->obj = obj; ! return parm; ! } ! ! if ((*env)->IsInstanceOf(env, obj, Class_CULong)) { ! parm->tag = 'l'; ! mid = (*env)->GetMethodID(env, Class_CULong, "getValue", "()J"); parm->value.l = (*env)->CallLongMethod(env, obj, mid); parm->obj = obj; *************** *** 483,491 **** *pp = ConvParam(env, arg, i+1); if (!*pp) { ! jclass newExcCls; ! char buf[200]; ! sprintf(buf, "Error while constructing argument %d:\n", i+1); ! newExcCls = (*env)->FindClass(env, "ctypes/java/CException"); ! (*env)->ThrowNew(env, newExcCls, buf); goto error; /* leaking ? */ --- 491,499 ---- *pp = ConvParam(env, arg, i+1); if (!*pp) { ! //jclass newExcCls; ! //char buf[200]; ! //sprintf(buf, "Error while constructing argument %d:\n", i+1); ! //newExcCls = (*env)->FindClass(env, "ctypes/java/CException"); ! //(*env)->ThrowNew(env, newExcCls, buf); goto error; /* leaking ? */ |
From: Bradley L S. <bs...@us...> - 2005-11-08 01:13:54
|
Update of /cvsroot/ctypes/ctypes-java/src/test/ctypes/java/test/generic In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23894/src/test/ctypes/java/test/generic Added Files: TestUnion.java Log Message: Union support --- NEW FILE: TestUnion.java --- /* Copyright (c) 2004 Bradley Schatz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package ctypes.java.test.generic; import junit.framework.TestCase; import ctypes.java.CAddress; import ctypes.java.CBuffer; import ctypes.java.CChar; import ctypes.java.CException; import ctypes.java.CInt; import ctypes.java.CIntPtr; import ctypes.java.CLong; import ctypes.java.CLongLong; import ctypes.java.CShort; import ctypes.java.CString; import ctypes.java.CULong; import ctypes.java.CUnion; /** * @author bradley * */ public class TestUnion extends TestCase { public TestUnion(String arg0) { super(arg0); } public class IntCharUnion extends CUnion { public CInt i; public CChar c; } public void testCIntandCChar() { try { CUnion u = new IntCharUnion(); u.setValue(new CInt(100)); u.pin(); CInt i = (CInt) u.getValue(CInt.class); assertEquals(100, i.getValue()); u.setValue(new CInt(101)); i = (CInt) u.getValue(CInt.class); assertEquals(101, i.getValue()); u.setValue(new CChar('a')); CChar c = (CChar) u.getValue(CChar.class); assertEquals('a', c.getValue()); } catch (Exception e) { fail(); } } public void testUndeclaredType() { try { CUnion u = new IntCharUnion(); u.setValue(new CInt(100)); u.pin(); CString i = (CString) u.getValue(CString.class); fail("Undeclared type."); } catch (IllegalArgumentException ex) { } catch (CException ex) { fail("Unexpected CException"); } } } |
From: Bradley L S. <bs...@us...> - 2005-11-08 01:13:54
|
Update of /cvsroot/ctypes/ctypes-java/src/test/ctypes/java/test In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23894/src/test/ctypes/java/test Modified Files: TestAllWin32.java Log Message: Union support Index: TestAllWin32.java =================================================================== RCS file: /cvsroot/ctypes/ctypes-java/src/test/ctypes/java/test/TestAllWin32.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** TestAllWin32.java 15 Apr 2005 03:15:47 -0000 1.4 --- TestAllWin32.java 8 Nov 2005 01:13:38 -0000 1.5 *************** *** 42,45 **** --- 42,46 ---- suite.addTest(new TestSuite(BuffersTest.class)); suite.addTest(new TestSuite(StructTest.class)); + suite.addTest(new TestSuite(TestUnion.class)); suite.addTest(new TestSuite(TestChars.class)); suite.addTest(new TestSuite(ReturnPointersTest.class)); |
From: Bradley L S. <bs...@us...> - 2005-11-08 01:13:54
|
Update of /cvsroot/ctypes/ctypes-java/src/java/ctypes/java In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23894/src/java/ctypes/java Modified Files: CBuffer.java Added Files: CUnion.java Log Message: Union support --- NEW FILE: CUnion.java --- /* Copyright (c) 2003 Bradley Schatz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package ctypes.java; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import com.sun.org.apache.bcel.internal.generic.GETSTATIC; /** * @author bradley * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class CUnion extends CType { protected CType[] candidateTypes = null; protected CType value = null; int allocated = 0; protected boolean isCandidateTypesProcessed = false; /** * @param size * @throws Exception */ public CUnion() { super(); } public CUnion(CType[] types) { super() ; candidateTypes = types; isCandidateTypesProcessed = true; } public void setAddress(CAddress handle, CType.SyncDirection syncDirection) throws CException { if (handle != CAddress.NULL && !isMemoryBacked()) { super.setAddress(handle, syncDirection); // now link each struct element onto the // memory buffer value.setAddress(handle, syncDirection); } } public int sizeOf() { if (!isCandidateTypesProcessed ) { processClass(); isCandidateTypesProcessed = true; } int maxSize = 0; // first determine the size of the struct for (int i = 0 ; i < candidateTypes.length ; i++) { if (candidateTypes[i].sizeOf() > maxSize) { maxSize = candidateTypes[i].sizeOf(); } } return maxSize; } public CUnion(int size) throws CException { super(); candidateTypes = new CType[size]; } /** * @return */ public CType[] getCandidateTypes() { if (!isCandidateTypesProcessed ) { processClass(); } return candidateTypes; } /** * @param types */ public void setCandidateTypes(CType[] types) { candidateTypes = types; isCandidateTypesProcessed = false; } public void pin() throws CException { isCandidateTypesProcessed = false; super.pin(); } protected CAddress allocate(int size) throws CException { this.size = size; caddress = CMalloc.malloc(size); address = caddress.getValue(); // we arent yet _fully_ memory backed memoryBacked = false; isAtomic = false; return caddress; } public void dump(StringBuffer buf, int level) throws CException { if (!isCandidateTypesProcessed) { processClass(); } super.dump(buf, level); value.dump(buf, level + 1); } public void dump(int level) throws CException { if (!isCandidateTypesProcessed) { processClass(); } super.dump(level); value.dump(level+1); } public int getLength() { if (!isCandidateTypesProcessed ) { processClass(); } return 1; } void processClass() { ArrayList l = new ArrayList(); processClass(this.getClass(), l); if (l.size() > 0) { candidateTypes = new CType[l.size()]; for (int i=0; i < l.size() ; i++) { candidateTypes[i] = (CType) l.get(i); } } isCandidateTypesProcessed = false; } void processClass(Class c, ArrayList fields) { if (!c.equals(CUnion.class)) { processClass(c.getSuperclass(), fields); } Field[] f = c.getDeclaredFields(); for (int i = 0 ; i < f.length ; i++) { Field field = f[i]; int modifiers = field.getModifiers(); if (Modifier.isPublic(modifiers) && ! Modifier.isStatic(modifiers)) { try { Object val = f[i].get(this); if (val == null) { try { val = f[i].getType().newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } } fields.add(val); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } /** * @return Returns the value. */ public CType getValue() { return value; } protected CType createInstance(Class klass) throws CException { try { CType o = (CType) klass.newInstance(); o.setAddress(getAddress(), CType.SyncDirection.ToJava); return o; } catch (Exception ex) { throw new CException(ex); } } public CType getValue(Class klass) throws CException { for (int i = 0 ; i < candidateTypes.length ; i++) { if (candidateTypes[i].getClass().equals(klass)) { return createInstance(klass); } } throw new IllegalArgumentException("Class " + klass.getName() + " not in Union"); } /** * @param value The value to set. */ public void setValue(CType value) throws CException { this.value = value; hasValue = true; if (isMemoryBacked()) { value.pin(); CBuffer src = new CBuffer(value.getAddress(), value.sizeOf()); CBuffer dest = new CBuffer(getAddress(), sizeOf()); byte[] buf= src.getData(); dest.setData(buf); } } } Index: CBuffer.java =================================================================== RCS file: /cvsroot/ctypes/ctypes-java/src/java/ctypes/java/CBuffer.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** CBuffer.java 29 Sep 2005 01:25:19 -0000 1.6 --- CBuffer.java 8 Nov 2005 01:13:38 -0000 1.7 *************** *** 32,35 **** --- 32,41 ---- } + public CBuffer(CAddress handle, int size) { + super(handle); + setSize(size); + memoryBacked = true; + } + public CBuffer(CType t) throws CException { CAddress caddress = allocate(t.sizeOf()); |
Update of /cvsroot/ctypes/ctypes/comtypes/unittests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv7110 Removed Files: Tag: branch_1_0 ut.py test_word.py test_wmi.py test_typeinfo.py test_safearray.py test_msscript.py test_ie.py test_getactiveobj.py test_excel.py test_createwrappers.py test_client.py test_basic.py test_GUID.py test_DISPPARAMS.py setup.py runtests.py .cvsignore Log Message: Moved tests to comtypes.test package. --- .cvsignore DELETED --- --- test_getactiveobj.py DELETED --- --- test_ie.py DELETED --- --- ut.py DELETED --- --- test_GUID.py DELETED --- --- test_word.py DELETED --- --- runtests.py DELETED --- --- test_wmi.py DELETED --- --- test_DISPPARAMS.py DELETED --- --- test_basic.py DELETED --- --- test_excel.py DELETED --- --- test_safearray.py DELETED --- --- test_createwrappers.py DELETED --- --- setup.py DELETED --- --- test_client.py DELETED --- --- test_msscript.py DELETED --- --- test_typeinfo.py DELETED --- |
From: Thomas H. <th...@us...> - 2005-11-04 08:07:32
|
Update of /cvsroot/ctypes/ctypes In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18973 Modified Files: Tag: branch_1_0 setup.py Log Message: Fix typo. Index: setup.py =================================================================== RCS file: /cvsroot/ctypes/ctypes/setup.py,v retrieving revision 1.122.2.6 retrieving revision 1.122.2.7 diff -C2 -d -r1.122.2.6 -r1.122.2.7 *** setup.py 4 Nov 2005 07:34:32 -0000 1.122.2.6 --- setup.py 4 Nov 2005 08:07:21 -0000 1.122.2.7 *************** *** 63,68 **** self.refcounts = 0 if sys.platform == "win32": ! ## self.test_dirs = "ctypes.test,ctypes.com.test,comtypes.test" ! self.tests = "ctypes.test,ctypes.com.test" else: self.tests = "ctypes.test" --- 63,68 ---- self.refcounts = 0 if sys.platform == "win32": ! self.tests = "ctypes.test,ctypes.com.test,comtypes.test" ! ## self.tests = "ctypes.test,ctypes.com.test" else: self.tests = "ctypes.test" |
From: Thomas H. <th...@us...> - 2005-11-04 07:44:52
|
Update of /cvsroot/ctypes/ctypes/win32/com/test In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv12281 Added Files: Tag: branch_1_0 test_word.py test_variant.py test_sysalloc.py test_safearray.py test_perf.py test_comobject.py __init__.py .cvsignore Log Message: Move ctypes.com tests into the ctypes.com.test package. --- NEW FILE: .cvsignore --- *.pyc *.pyo --- NEW FILE: test_comobject.py --- import unittest, os, sys from ctypes import * def get_refcnt(comptr): if not comptr: return 0 comptr.AddRef() return comptr.Release() class Test_EmptyComPointer(unittest.TestCase): # This test makes sure that calling a COM method on a COM # interface pointer raises a ValueError, when the interface # pointer points to NULL. def setUp(self): from ctypes.com import IUnknown self._orig_del = POINTER(IUnknown).__del__ # We replace the __del__ method (which calls self.Release(), # because it would crash. def __del__(self): pass POINTER(IUnknown).__del__ = __del__ def tearDown(self): from ctypes.com import IUnknown POINTER(IUnknown).__del__ = self._orig_del def test_comcrash(self): from ctypes.com import IUnknown p = pointer(IUnknown()) try: p.AddRef() except ValueError, message: self.failUnlessEqual(str(message), "COM method call without VTable") else: self.fail("Exception expected") class ComTestCase(unittest.TestCase): def __init__(self, *args): unittest.TestCase.__init__(self, *args) global COMObject, IUnknown, GUID, STDMETHOD, HRESULT from ctypes.com import COMObject, IUnknown, GUID, STDMETHOD, HRESULT def setUp(self): class IObjectWithSite(IUnknown): _iid_ = GUID("{FC4801A3-2BA9-11CF-A229-00AA003D7352}") _methods_ = IUnknown._methods_ + [ (STDMETHOD(HRESULT, "SetSite", POINTER(IUnknown))), (STDMETHOD(HRESULT, "GetSite", POINTER(GUID), POINTER(c_void_p)))] class Factory(object): def LockServer(self, *args): pass class MyObject(COMObject): _factory = Factory() _com_interfaces_ = [IObjectWithSite] def IObjectWithSite_SetSite(self, this, pUnkSite): self.m_site = pUnkSite return 0 # S_OK self.impl = MyObject() def tearDown(self): self.impl = None import gc gc.collect() ################ def test_site(self): impl = self.impl p = pointer(impl._com_pointers_[0][1]) self.failUnlessEqual(impl._refcnt, 0) p.AddRef() self.failUnlessEqual(impl._refcnt, 1) p.SetSite(p) self.failUnlessEqual(impl._refcnt, 2) p.SetSite(None) self.failUnlessEqual(impl._refcnt, 1) del p self.failUnlessEqual(impl._refcnt, 0) def test_comobject(self): impl = self.impl self.failUnlessEqual(impl._refcnt, 0) p = pointer(impl._com_pointers_[0][1]) p.AddRef() self.failUnlessEqual(impl._refcnt, 1) self.failUnlessEqual(get_refcnt(p), 1) del p self.failUnlessEqual(impl._refcnt, 0) def test_qi(self): impl = self.impl self.failUnlessEqual(impl._refcnt, 0) p = pointer(impl._com_pointers_[0][1]) p.AddRef() self.failUnlessEqual(get_refcnt(p), 1) p2 = POINTER(IUnknown)() p.QueryInterface(byref(IUnknown._iid_), byref(p2)) self.failUnlessEqual(get_refcnt(p), 2) del p2 self.failUnlessEqual(get_refcnt(p), 1) def test_from_progid(self): g = GUID.from_progid("InternetExplorer.Application") self.failUnlessEqual(g, GUID("{0002DF01-0000-0000-C000-000000000046}")) def test_GUID(self): g1 = GUID("{00000000-0001-0002-0003-000000000000}") g2 = GUID("{00000000-0001-0002-0003-000000000000}") g3 = GUID("{00000000-0001-0002-0003-000000000001}") self.failUnlessEqual(g1, g2) # for now, GUID instances are unhashable. ## d = {} ## d[g1] = None ## self.failUnlessEqual(g1 in d, True) ## self.failUnlessEqual(g2 in d, True) ## self.failUnlessEqual(g3 in d, False) ################################################################ if __name__ == '__main__': unittest.main() --- NEW FILE: test_perf.py --- import sys, re # Some preformance measurements def timeit(*args): from timeit import main from cStringIO import StringIO prev_stdout = sys.stdout sys.stdout = StringIO() main(args) out = sys.stdout.getvalue() sys.stdout = prev_stdout match = re.search(r"(\d+\.\d*|\d+) usec", out) time = float(match.group(1)) print "%8.2f: %s" % (time, args[-1]) ################################################################ import ctypes from ctypes import * class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] class RECT(Structure): _fields_ = [("ul", POINT), ("lr", POINT)] class Class(object): pass def get_fd(): # get a FUNCDESC instance from a typelib from comtypes.typeinfo import LoadTypeLibEx from comtypes import GUID tlib = LoadTypeLibEx("shdocvw.dll") # IWebBrowser interface tinfo = tlib.GetTypeInfoOfGuid(GUID("{EAB22AC1-30C1-11CF-A7EB-0000C05BAE0B}")) tcomp = tinfo.GetTypeComp() kind, fd = tcomp.Bind("Navigate") return fd ################################################################ if __name__ == "__main__": print "ctypes version:", ctypes.__version__ print "python version:", sys.version timeit("-s", "from test_perf import Class", "Class()") timeit("-s", "from test_perf import POINT", "POINT()") timeit("-s", "from test_perf import RECT", "RECT()") timeit("-s", "from test_perf import POINT; point = POINT()", "point.y") timeit("-s", "from test_perf import RECT; rect = RECT()", "rect.lr") timeit("-s", "from test_perf import get_fd; fd = get_fd()", "fd.lprgelemdescParam") timeit("-s", "from test_perf import get_fd; fd = get_fd()", "fd.lprgelemdescParam[0]") timeit("-s", "from test_perf import get_fd; fd = get_fd()", "fd.lprgelemdescParam[1]") timeit("-s", "from test_perf import get_fd; fd = get_fd()", "fd.lprgelemdescParam[1].tdesc") timeit("-s", "from test_perf import get_fd; fd = get_fd()", "fd.lprgelemdescParam[1].tdesc.vt") timeit("-s", "from test_perf import get_fd; fd = get_fd()", "fd.lprgelemdescParam[1].tdesc._.lptdesc[0].vt") timeit('-s', "from ctypes import c_int", "c_int()") timeit('-s', "from ctypes import c_int", "c_int(42)") timeit('-s', "from ctypes.com.automation import VARIANT", "VARIANT() # ctypes.com") timeit('-s', "from ctypes.com.automation import VARIANT; variant = VARIANT(3)", "variant.value # ctypes.com") timeit('-s', "from ctypes.com.automation import VARIANT; variant = VARIANT()", "variant.value = 3.14 # ctypes.com") try: import comtypes except ImportError: pass else: timeit('-s', "from comtypes.automation import VARIANT", "VARIANT() # comtypes") timeit('-s', "from comtypes.automation import VARIANT; variant = VARIANT(3)", "variant.value # comtypes") timeit('-s', "from comtypes.automation import VARIANT; variant = VARIANT()", "variant.value = 3.14 # comtypes") timeit('-s', "from comtypes.automation import VARIANT; variant = VARIANT()", "variant.value = (3.14, None, u'foo') # comtypes") timeit('-s', "from comtypes.automation import VARIANT; variant = VARIANT((3.14, None, 'foo'))", "variant.value # comtypes") # on my machine which has around 30000 pystones/second: ##ctypes version: 0.9.2 ##python version: 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] ## 0.38: Class() ## 1.97: POINT() ## 1.98: RECT() ## 0.24: point.y ## 2.43: rect.lr ## 7.21: fd.lprgelemdescParam ## 10.90: fd.lprgelemdescParam[0] ## 12.00: fd.lprgelemdescParam[1] ## 15.30: fd.lprgelemdescParam[1].tdesc ## 16.00: fd.lprgelemdescParam[1].tdesc.vt ## 26.20: fd.lprgelemdescParam[1].tdesc.u.lptdesc[0].vt ## 1.80: c_int() ## 1.97: c_int(42) ## 2.93: VARIANT() # ctypes.com ## 5.30: variant.value # ctypes.com ## 11.60: variant.value = 3.14 # ctypes.com ##ctypes version: 0.9.3 ##python version: 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] ## 0.37: Class() ## 0.96: POINT() ## 0.94: RECT() ## 0.25: point.y ## 1.94: rect.lr ## 7.16: fd.lprgelemdescParam ## 10.10: fd.lprgelemdescParam[0] ## 10.00: fd.lprgelemdescParam[1] ## 12.30: fd.lprgelemdescParam[1].tdesc ## 13.70: fd.lprgelemdescParam[1].tdesc.vt ## 19.30: fd.lprgelemdescParam[1].tdesc.u.lptdesc[0].vt ## 1.16: c_int() ## 1.34: c_int(42) ## 2.40: VARIANT() # ctypes.com ## 5.25: variant.value # ctypes.com ## 11.20: variant.value = 3.14 # ctypes.com ## 2.08: VARIANT() # comtypes ## 4.99: variant.value # comtypes ## 11.40: variant.value = 3.14 # comtypes ##ctypes version: 0.9.8 (not yet released, 2005/05/11) ##python version: 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] ## 0.41: Class() ## 0.48: POINT() ## 0.48: RECT() ## 0.26: point.y ## 0.56: rect.lr ## 0.61: fd.lprgelemdescParam ## 1.14: fd.lprgelemdescParam[0] ## 1.20: fd.lprgelemdescParam[1] ## 1.76: fd.lprgelemdescParam[1].tdesc ## 1.93: fd.lprgelemdescParam[1].tdesc.vt ## 3.60: fd.lprgelemdescParam[1].tdesc._.lptdesc[0].vt ## 0.48: c_int() ## 0.72: c_int(42) ## 1.75: VARIANT() # ctypes.com ## 3.21: variant.value # ctypes.com ## 8.23: variant.value = 3.14 # ctypes.com ## 1.46: VARIANT() # comtypes ## 3.11: variant.value # comtypes ## 8.57: variant.value = 3.14 # comtypes ##ctypes version: 0.9.8 (not yet released, 2005/05/12) ##python version: 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] ## 0.40: Class() ## 0.47: POINT() ## 0.48: RECT() ## 0.25: point.y ## 0.49: rect.lr ## 0.49: fd.lprgelemdescParam ## 0.96: fd.lprgelemdescParam[0] ## 0.99: fd.lprgelemdescParam[1] ## 1.48: fd.lprgelemdescParam[1].tdesc ## 1.63: fd.lprgelemdescParam[1].tdesc.vt ## 3.02: fd.lprgelemdescParam[1].tdesc._.lptdesc[0].vt ## 0.48: c_int() ## 0.71: c_int(42) ## 1.75: VARIANT() # ctypes.com ## 3.17: variant.value # ctypes.com ## 8.07: variant.value = 3.14 # ctypes.com ## 1.51: VARIANT() # comtypes ## 3.12: variant.value # comtypes ## 8.75: variant.value = 3.14 # comtypes --- NEW FILE: __init__.py --- # --- NEW FILE: test_word.py --- from ctypes.com import hresult from ctypes.com.client import Dispatch from ctypes.test import requires requires("ui") import unittest class Word(unittest.TestCase): def test_word(self): try: word = Dispatch("Word.Application") except WindowsError, details: if details.errno == hresult.CO_E_CLASSSTRING: self.fail("It seems Word is not installed...") raise word.Visible = 1 doc = word.Documents.Add() wrange = doc.Range() for i in range(10): wrange.InsertAfter("Hello from ctypes via COM %d\n" % i) paras = doc.Paragraphs for i in range(len(paras)): p = paras[i]() p.Font.ColorIndex = i+1 p.Font.Size = 12 + (2 * i) doc.Close(SaveChanges=0) word.Quit() if __name__ == '__main__': unittest.main() --- NEW FILE: test_sysalloc.py --- import unittest from ctypes import * from ctypes.com import mallocspy, ole32 from ctypes.com.automation import BSTR, VARIANT import _ctypes_test class MallocSpyTest(unittest.TestCase): def setUp(self): # ctypes.com has called CoInitialize, but we must install the spy # in uninitialized state. ole32.CoUninitialize() self.expect = None self.mallocspy = mallocspy.MallocSpy() self.mallocspy.register() ole32.CoInitialize(None) def tearDown(self): try: try: # Even if tests fail or crash, we have to make sure we can # shutdown safely. The problem is that mallocspy cannot be # revoked completely while there are still unfreed memory # blocks which have been allocated while it was registered. # # So, we must delete *all* COM objects we still have anywhere, # even if an error occurred somewhere, and then shutdown COM, # BEFORE Python exits. try: 1/0 except: pass ole32.CoUninitialize() # Now, check the desired test outcome: self.failUnlessEqual(len(self.mallocspy.active_blocks()), self.expect) finally: self.mallocspy.revoke(warn=0) finally: # we must restore the environment to the state we found it! ole32.CoInitialize(None) ################ def test_leak(self): # Allocate 10 BSTR's without freeing them, and make sure the # leak is detected for i in range(10): windll.oleaut32.SysAllocString(unicode("Python is cool %s" % i)) self.expect = 10 def test_no_leak(self): # Allocate 10 BSTR's then free them, and make sure *no* leak # is detected L = [] for i in range(10): b = windll.oleaut32.SysAllocString(unicode("Python is cool %s" % i)) L.append(b) for b in L: windll.oleaut32.SysFreeString(b) self.expect = 0 def test_GetString_C(self): # GetString is this function, implemented in C: # # EXPORT(void) GetString(BSTR *pbstr) # { # *pbstr = SysAllocString(L"Goodbye!"); # } GetString = CDLL(_ctypes_test.__file__).GetString # XXX Explain why we cannot create b outside the loop! # And why we cannot do anything against this :-) for i in range(32): b = BSTR() GetString(byref(b)) self.expect = 0 def test_GetString_Python(self): # Same test as before, but with ctypes implemented C function PROTO = WINFUNCTYPE(None, POINTER(BSTR), c_int) def func(pbstr, i): pbstr[0] = "%s %s" % ("Spam, spam, and spam", i) func = PROTO(func) for i in range(32): b = BSTR() func(byref(b), i) self.failUnlessEqual(b.value, "%s %s" % ("Spam, spam, and spam", i)) self.expect = 0 def test_BSTR_alloc(self): for i in range(32): BSTR(u"Hello World %d" % i) self.expect = 0 def test_BSTR_pointer(self): for i in range(32): p = pointer(BSTR()) p.value = u"Hello World %d" % i self.expect = 0 def test_VARIANT(self): # We still have to clear variants manually, to avoid memory leaks. for i in range(32): v = VARIANT("Hello, World") v.value = None self.expect = 0 def test_VARIANT_memleak(self): # This demonstrates the memory leak: for i in range(32): VARIANT("Hello, World") self.expect = 32 # Offtopic for this test: # XXX These need better error messages: ## POINTER(BSTR()) # TypeError: unhashable type ## pointer(BSTR) # TypeError: _type_ must have storage info ################################################################ if __name__ == "__main__": unittest.main() --- NEW FILE: test_safearray.py --- import unittest, os from ctypes import * from ctypes.com import IUnknown, GUID from ctypes.com.automation import VARIANT, LoadTypeLibEx, \ VT_ARRAY, VT_VARIANT, VT_I4, VT_INT, oleaut32, IDispatch # test VT_ARRAY in VARIANTS class SAFEARRAYTest(unittest.TestCase): def test_VT_VARIANT(self): v = VARIANT() # lists... v.value = [1, "spam", [None, "foo"]] self.failUnlessEqual(v.value, [1, "spam", [None, "foo"]]) self.failUnlessEqual(v.vt, VT_VARIANT | VT_ARRAY) dim = oleaut32.SafeArrayGetDim(v._.voidp) self.failUnlessEqual(dim, 1) # and tuples. v.value = (1, "spam", (None, "foo")) self.failUnlessEqual(v.value, [1, "spam", [None, "foo"]]) def test_VT_INT(self): import array data = array.array("i", (1, 2, 3, 4, 5)) v = VARIANT() v.value = data self.failUnlessEqual(v.vt, VT_INT | VT_ARRAY) dim = oleaut32.SafeArrayGetDim(v._.voidp) self.failUnlessEqual(dim, 1) def _getrefcnt(self, comobj): comobj.AddRef() return comobj.Release() def test_VT_UNKNOWN(self): tlb = LoadTypeLibEx(r"c:\windows\system32\shdocvw.dll") self.failUnlessEqual(self._getrefcnt(tlb), 1) v = VARIANT() v.value = tlb self.failUnlessEqual(self._getrefcnt(tlb), 2) v.value = None self.failUnlessEqual(self._getrefcnt(tlb), 1) v.value = [tlb] self.failUnlessEqual(self._getrefcnt(tlb), 2) pcom = v.value[0] self.failUnlessEqual(self._getrefcnt(tlb), 3) self.failUnlessEqual(self._getrefcnt(pcom), 3) # ITypeLib derives from IUnknown, and VARIANT can only store IUnknown or IDispatch # pointers, so: self.failUnlessEqual(type(pcom), POINTER(IUnknown)) del pcom self.failUnlessEqual(self._getrefcnt(tlb), 2) v.value = None self.failUnlessEqual(self._getrefcnt(tlb), 1) def test_VT_DISPATCH(self): from ctypes.com.client import Dispatch p = Dispatch("MSScriptControl.ScriptControl") # any inproc IDispatch will do pdisp = p._comobj self.failUnlessEqual(self._getrefcnt(pdisp), 1) v = VARIANT() v.value = pdisp self.failUnlessEqual(self._getrefcnt(pdisp), 2) v.value = None self.failUnlessEqual(self._getrefcnt(pdisp), 1) v.value = [pdisp] self.failUnlessEqual(self._getrefcnt(pdisp), 2) pcom = v.value[0] self.failUnlessEqual(self._getrefcnt(pdisp), 3) self.failUnlessEqual(self._getrefcnt(pcom), 3) # ITypeLib derives from IUnknown, and VARIANT can only store IUnknown or IDispatch # pointers, so: self.failUnlessEqual(type(pcom), POINTER(IDispatch)) del pcom self.failUnlessEqual(self._getrefcnt(pdisp), 2) v.value = None self.failUnlessEqual(self._getrefcnt(pdisp), 1) ## def test_multidim() if __name__ == "__main__": unittest.main() --- NEW FILE: test_variant.py --- import unittest, os from ctypes import * from ctypes.com import IUnknown, GUID from ctypes.com.automation import VARIANT, LoadTypeLibEx, DISPPARAMS, LoadRegTypeLib def get_refcnt(comptr): # return the COM reference count of a COM interface pointer if not comptr: return 0 comptr.AddRef() return comptr.Release() class VariantTestCase(unittest.TestCase): def test_com_refcounts(self): # typelib for Internet Explorer tlb = LoadRegTypeLib(GUID("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}"), 1, 1, 0) self.failUnlessEqual(get_refcnt(tlb), 1) p = POINTER(IUnknown)() tlb.QueryInterface(byref(IUnknown._iid_), byref(p)) self.failUnlessEqual(get_refcnt(tlb), 2) del p self.failUnlessEqual(get_refcnt(tlb), 1) def test_com_pointers(self): # Storing a COM interface pointer in a VARIANT increments the refcount, # changing the variant to contain something else decrements it tlb = LoadRegTypeLib(GUID("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}"), 1, 1, 0) self.failUnlessEqual(get_refcnt(tlb), 1) v = VARIANT(tlb) self.failUnlessEqual(get_refcnt(tlb), 2) p = v.value self.failUnlessEqual(get_refcnt(tlb), 3) del p self.failUnlessEqual(get_refcnt(tlb), 2) v.value = None self.failUnlessEqual(get_refcnt(tlb), 1) def test_null_com_pointers(self): p = POINTER(IUnknown)() self.failUnlessEqual(get_refcnt(p), 0) v = VARIANT(p) self.failUnlessEqual(get_refcnt(p), 0) def test_dispparams(self): # DISPPARAMS is a complex structure, well worth testing. d = DISPPARAMS() d.rgvarg = (VARIANT * 3)() # XXX The following line fails, which is a real bug in ctypes: # SystemError: ...\Objects\listobject.c:105: bad argument to internal function # # Update: this bug is fixed, now I have to rememeber what I wanted to test here. d.rgvarg[0].value = 1 def test_pythonobjects(self): objects = [None, 42, 3.14, True, False, "abc", u"abc", 7L] for x in objects: v = VARIANT(x) self.failUnlessEqual(x, v.value) def test_integers(self): import sys v = VARIANT() v.value = sys.maxint self.failUnlessEqual(v.value, sys.maxint) self.failUnlessEqual(type(v.value), int) v.value += 1 self.failUnlessEqual(v.value, sys.maxint+1) self.failUnlessEqual(type(v.value), float) v.value = 1L self.failUnlessEqual(v.value, 1) self.failUnlessEqual(type(v.value), int) def test_datetime(self): import datetime now = datetime.datetime.now() v = VARIANT() v.value = now from ctypes.com.automation import VT_DATE self.failUnlessEqual(v.vt, VT_DATE) self.failUnlessEqual(v.value, now) def test_BSTR(self): from ctypes.com.automation import BSTR, VT_BSTR v = VARIANT() v.value = u"abc\x00123\x00" self.failUnlessEqual(v.value, "abc\x00123\x00") v.value = None # manually clear the variant v._.VT_I4 = 0 # NULL pointer BSTR should be handled as empty string v.vt = VT_BSTR self.failUnlessEqual(v.value, "") class ArrayTest(unittest.TestCase): def test_double(self): import array for typecode in "df": # because of FLOAT rounding errors, whi will only work for # certain values! a = array.array(typecode, [1.0, 2.0, 3.0, 4.5]) v = VARIANT() v.value = a self.failUnlessEqual(v.value, [1.0, 2.0, 3.0, 4.5]) def test_int(self): import array for typecode in "bhiBHIlL": a = array.array(typecode, [1, 1, 1, 1]) v = VARIANT() v.value = a self.failUnlessEqual(v.value, [1, 1, 1, 1]) ################################################################ if __name__ == '__main__': unittest.main() |
Update of /cvsroot/ctypes/ctypes/unittests/com In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv12257 Removed Files: Tag: branch_1_0 test_word.py test_variant.py test_sysalloc.py test_safearray.py test_perf.py test_comobject.py .cvsignore Log Message: Move ctypes.com tests into the ctypes.com.test package. --- .cvsignore DELETED --- --- test_comobject.py DELETED --- --- test_perf.py DELETED --- --- test_word.py DELETED --- --- test_sysalloc.py DELETED --- --- test_safearray.py DELETED --- --- test_variant.py DELETED --- |
From: Thomas H. <th...@us...> - 2005-11-04 07:41:20
|
Update of /cvsroot/ctypes/ctypes/win32/com/test In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11496/test Log Message: Directory /cvsroot/ctypes/ctypes/win32/com/test added to the repository --> Using per-directory sticky tag `branch_1_0' |
From: Thomas H. <th...@us...> - 2005-11-04 07:36:55
|
Update of /cvsroot/ctypes/ctypes/ctypes/test In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10812 Modified Files: Tag: branch_1_0 runtests.py Log Message: get_tests() and main() take a package name argument. New function run_tests(). Index: runtests.py =================================================================== RCS file: /cvsroot/ctypes/ctypes/ctypes/test/Attic/runtests.py,v retrieving revision 1.1.2.1 retrieving revision 1.1.2.2 diff -C2 -d -r1.1.2.1 -r1.1.2.2 *** runtests.py 3 Nov 2005 19:49:19 -0000 1.1.2.1 --- runtests.py 4 Nov 2005 07:36:46 -0000 1.1.2.2 *************** *** 15,17 **** if __name__ == "__main__": ! sys.exit(ctypes.test.main()) --- 15,17 ---- if __name__ == "__main__": ! sys.exit(ctypes.test.main(ctypes.test)) |
From: Thomas H. <th...@us...> - 2005-11-04 07:36:43
|
Update of /cvsroot/ctypes/ctypes/ctypes/test In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10763 Modified Files: Tag: branch_1_0 __init__.py Log Message: get_tests() and main() take a package name argument. New function run_tests(). Index: __init__.py =================================================================== RCS file: /cvsroot/ctypes/ctypes/ctypes/test/Attic/__init__.py,v retrieving revision 1.1.2.1 retrieving revision 1.1.2.2 diff -C2 -d -r1.1.2.1 -r1.1.2.2 *** __init__.py 3 Nov 2005 19:49:19 -0000 1.1.2.1 --- __init__.py 4 Nov 2005 07:36:35 -0000 1.1.2.2 *************** *** 32,44 **** raise ResourceDenied(msg) ! def get_tests(mask, verbosity): """Return a list of skipped test modules, and a list of test cases.""" ! if not mask.endswith(".py"): ! mask += ".py" tests = [] skipped = [] ! for fname in glob.glob(mask): try: ! mod = __import__(os.path.splitext(fname)[0]) except ResourceDenied, detail: skipped.append(fname) --- 32,45 ---- raise ResourceDenied(msg) ! def get_tests(package, mask, verbosity): """Return a list of skipped test modules, and a list of test cases.""" ! test_dir = package.__path__[0] ! import fnmatch tests = [] skipped = [] ! for fname in fnmatch.filter(os.listdir(test_dir), mask): ! ## for fname in glob.glob(mask): try: ! mod = __import__("%s.%s" % (package.__name__, fname[:-3]), globals(), locals(), ['*']) except ResourceDenied, detail: skipped.append(fname) *************** *** 130,135 **** ! def main(): ! os.chdir(os.path.dirname(sys.argv[0])) try: opts, args = getopt.getopt(sys.argv[1:], "rqvu:") --- 131,135 ---- ! def main(package): try: opts, args = getopt.getopt(sys.argv[1:], "rqvu:") *************** *** 157,161 **** if args: mask = args[0] ! skipped, testcases = get_tests(mask, verbosity) runner = TestRunner(verbosity=verbosity) --- 157,166 ---- if args: mask = args[0] ! ! run_tests(package, mask, verbosity, search_leaks) ! ! ! def run_tests(package, mask, verbosity, search_leaks): ! skipped, testcases = get_tests(package, mask, verbosity) runner = TestRunner(verbosity=verbosity) |
From: Thomas H. <th...@us...> - 2005-11-04 07:34:40
|
Update of /cvsroot/ctypes/ctypes In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10385 Modified Files: Tag: branch_1_0 setup.py Log Message: Replace the test command by a much simpler one, which uses 'ctypes.test'. Running tests in a separate process is no longer supported. Add ctypes.test package. Index: setup.py =================================================================== RCS file: /cvsroot/ctypes/ctypes/setup.py,v retrieving revision 1.122.2.5 retrieving revision 1.122.2.6 diff -C2 -d -r1.122.2.5 -r1.122.2.6 *** setup.py 28 Oct 2005 18:11:23 -0000 1.122.2.5 --- setup.py 4 Nov 2005 07:34:32 -0000 1.122.2.6 *************** *** 47,248 **** user_options = [ ! ('test-dirs=', None, ! "comma-separated list of directories that contain the test definitions"), ! ('test-prefix=', None, ! "prefix to the testcase filename"), ! ('verbosity=', 'V', "verbosity"), ] def initialize_options(self): self.build_base = 'build' ! # these are decided only after 'build_base' has its final value ! # (unless overridden by the user or client) ! self.test_prefix = 'test_' ! self.verbosity = 1 if sys.platform == "win32": ! self.test_dirs = r"unittests,unittests\com" else: ! self.test_dirs = "unittests" # initialize_options() def finalize_options(self): ! try: ! self.verbosity = int(self.verbosity) ! except ValueError: ! raise DistutilsOptionError, \ ! "verbosity must be an integer" ! ! build = self.get_finalized_command('build') ! self.build_purelib = build.build_purelib ! self.build_platlib = build.build_platlib ! ! self.test_dirs = self.test_dirs.split(",") # finalize_options() - def extend_path(self): - # We must add the current directory to $PYTHONPATH for the unittests - # running as separate processes - pypath = os.environ.get("PYTHONPATH") - if pypath: - pypath = pypath.split(os.pathsep) + [] - else: - pypath = [] - if os.getcwd() in pypath: - return - os.environ["PYTHONPATH"] = os.pathsep.join(pypath) - def run(self): - import glob, unittest, time self.run_command('build') ! for direct in self.test_dirs: ! mask = os.path.join(direct, self.test_prefix + "*.py") ! test_files = glob.glob(mask) ! ! print "=== Testing in '%s' ===" % direct ! self.extend_path() ! ! self.testcases = [] ! self.ok = self.fail = self.errors = 0 ! self.tracebacks = [] ! ! start_time = time.time() ! for t in test_files: ! testcases = self.run_test(t) ! for case in testcases: ! if self.verbosity > 1: ! print >> sys.stderr, case ! elif self.verbosity == 1: ! if case.endswith("ok"): ! sys.stderr.write(".") ! elif case.endswith("FAIL"): ! sys.stderr.write("F") ! elif case.endswith("ERROR"): ! sys.stderr.write("E") ! else: ! sys.stderr.write("?") ! stop_time = time.time() ! ! print >> sys.stderr ! for f in self.tracebacks: ! print >> sys.stderr, "=" * 42 ! print >> sys.stderr, f[0] ! print >> sys.stderr, "-" * 42 ! print >> sys.stderr, "\n".join(f[1:]) ! print >> sys.stderr ! print >> sys.stderr, "-" * 70 ! print >> sys.stderr, "Ran %d tests in %.3fs" % (len(self.testcases), ! stop_time - start_time) ! print >> sys.stderr ! if self.fail + self.errors == 0: ! print >> sys.stderr, "OK" ! else: ! if self.errors: ! print >> sys.stderr, "FAILED (failures=%d, errors=%d)" % (self.fail, ! self.errors) ! else: ! print >> sys.stderr, "FAILED (failures=%d)" % self.fail # run() - def run_test(self, path): - # Run a test file in a separate process, and parse the output. - # Collect the results in the ok, fail, error, testcases and - # tracebacks instance vars. - # A sequence of testcase names together with their outcome is returned. - if self.verbosity > 1: - print "Running '%s run_remote_test.py %s'" % (sys.executable, path) - ret = os.system("%s run_remote_test.py %s" % (sys.executable, path)) - if ret: - print "CRASHED (%d)" % ret, path - cases = [] - o = open("test.output") - while 1: - line = o.readline() - if not line: - break - line = line.rstrip() - if line.startswith('test'): - cases.append(line) - if line.endswith("ok"): - self.ok += 1 - elif line.endswith("FAIL"): - self.fail += 1 - elif line.endswith("ERROR"): - self.errors += 1 - else: #? - self.errors += 1 - self.tracebacks.append([line, "Crashed"]) - elif line == "=" * 70: - # failure or error - name = o.readline().rstrip() - assert o.readline().rstrip() == "-" * 70 - tb = [name] - while 1: - data = o.readline() - if not data.rstrip(): - break - tb.append(data.rstrip()) - self.tracebacks.append(tb) - elif line.rstrip() == '-' * 70: - pass - elif line.startswith("Ran "): - pass - ## else: - ## print line - self.testcases.extend(cases) - return cases - # class test - class test_local(test): - description = "run the unittests (includes doctests)" - - # This also runs doctest testcases contained in the test modules - def run(self): - import glob, unittest, doctest, new - self.run_command('build') - - test_suites = [] - - for direct in self.test_dirs: - mask = os.path.join(direct, self.test_prefix + "*.py") - test_files = glob.glob(mask) - - print "=== Testing in '%s' ===" % direct - test_suites = [] - old_path = sys.path[:] - sys.path.insert(0, direct) - - try: - for pathname in test_files: - modname = os.path.splitext(pathname)[0].split(os.sep)[-1] - try: - mod = __import__(modname) - except Exception, e: - print >> sys.stderr, \ - "Could not import %s:\n %s" % (pathname, e) - continue - try: - suite = doctest.DocTestSuite(mod) - except ValueError: - pass - else: - test_suites.append(suite) - for name, obj in mod.__dict__.items(): - if name.startswith("_"): - continue - if type(obj) is type(unittest.TestCase) \ - and issubclass(obj, unittest.TestCase): - test_suites.append(unittest.makeSuite(obj)) - finally: - sys.path = old_path - suite = unittest.TestSuite(test_suites) - unittest.TextTestRunner(verbosity=self.verbosity).run(suite) - # class test_local - class my_build_py(build_py.build_py): --- 47,99 ---- user_options = [ ! ('tests=', 't', ! "comma-separated list of packages that contain test modules"), ! ('use-resources=', 'u', ! "resources to use - resource names are defined by tests"), ! ('refcounts', 'r', ! "repeat tests to search for refcount leaks (requires 'sys.gettotalrefcount')"), ] + boolean_options = ["refcounts"] + def initialize_options(self): self.build_base = 'build' ! ## self.test_prefix = 'test_' ! self.use_resources = "" ! self.refcounts = 0 if sys.platform == "win32": ! ## self.test_dirs = "ctypes.test,ctypes.com.test,comtypes.test" ! self.tests = "ctypes.test,ctypes.com.test" else: ! self.tests = "ctypes.test" # initialize_options() def finalize_options(self): ! if self.refcounts and not hasattr(sys, "gettotalrefcount"): ! raise DistutilsOptionError("refcount option requires Python debug build") ! self.tests = self.tests.split(",") ! self.use_resources = self.use_resources.split(",") # finalize_options() def run(self): self.run_command('build') ! import ctypes.test ! ctypes.test.use_resources.extend(self.use_resources) ! for name in self.tests: ! package = __import__(name, globals(), locals(), ['*']) ! print "Testing package", name ! ctypes.test.run_tests(package, ! "test_*.py", ! self.verbose, ! self.refcounts) # run() # class test class my_build_py(build_py.build_py): *************** *** 417,421 **** # the ctypes package # ! packages = ["ctypes", "ctypes.wrap", "ctypes.macholib"] package_dir = {} --- 268,272 ---- # the ctypes package # ! packages = ["ctypes", "ctypes.wrap", "ctypes.macholib", "ctypes.test"] package_dir = {} *************** *** 430,433 **** --- 281,287 ---- package_dir["ctypes.com.tools"] = "win32/com/tools" + packages.append("ctypes.test") + package_dir["ctypes.test"] = "win32/com/test" + ################################################################ # options for distutils, and ctypes.com samples *************** *** 507,512 **** cmdclass = {'test': test, 'build_py': my_build_py, 'build_ext': my_build_ext, ! 'clean': my_clean, 'install_data': my_install_data, ! 'testlocal': test_local}, options = setup_options ) --- 361,365 ---- cmdclass = {'test': test, 'build_py': my_build_py, 'build_ext': my_build_ext, ! 'clean': my_clean, 'install_data': my_install_data}, options = setup_options ) |
From: Thomas H. <th...@us...> - 2005-11-04 07:33:16
|
Update of /cvsroot/ctypes/ctypes In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10150 Modified Files: Tag: branch_1_0 README.txt Log Message: Bring in sync with current state. Index: README.txt =================================================================== RCS file: /cvsroot/ctypes/ctypes/README.txt,v retrieving revision 1.11.4.1 retrieving revision 1.11.4.2 diff -C2 -d -r1.11.4.1 -r1.11.4.2 *** README.txt 16 May 2005 23:29:19 -0000 1.11.4.1 --- README.txt 4 Nov 2005 07:33:05 -0000 1.11.4.2 *************** *** 49,53 **** To install ctypes from source, unpack the distribution, enter ! the ctypes-0.9.0 directory, and enter python setup.py build --- 49,53 ---- To install ctypes from source, unpack the distribution, enter ! the ctypes-0.9.x source directory, and enter python setup.py build *************** *** 58,69 **** set the environment variable CCASFLAGS="-Dno_live_support". ! To run the builtin unittests, enter python setup.py test - There may still be some problems on certain platforms, and the - tests may crash Python with a segfault - for this reason the - unittests are run in separate processes. - To install ctypes, enter --- 58,65 ---- set the environment variable CCASFLAGS="-Dno_live_support". ! To run the supplied tests, enter python setup.py test To install ctypes, enter *************** *** 85,89 **** example scripts demonstrating the use. ! Current version: 0.9.0 Homepage: http://starship.python.net/crew/theller/ctypes.html --- 81,85 ---- example scripts demonstrating the use. ! Current version: 0.9.9 Homepage: http://starship.python.net/crew/theller/ctypes.html *************** *** 92,96 **** ctypes license ! Copyright (c) 2000, 2001, 2002, 2003, 2004 Thomas Heller Permission is hereby granted, free of charge, to any person --- 88,92 ---- ctypes license ! Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005 Thomas Heller Permission is hereby granted, free of charge, to any person |
From: Thomas H. <th...@us...> - 2005-11-03 20:04:26
|
Update of /cvsroot/ctypes/ctypes/source In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv7413 Modified Files: Tag: branch_1_0 _ctypes.c Log Message: Provide PyTuple_Pack for Python 2.3. Index: _ctypes.c =================================================================== RCS file: /cvsroot/ctypes/ctypes/source/_ctypes.c,v retrieving revision 1.226.2.34 retrieving revision 1.226.2.35 diff -C2 -d -r1.226.2.34 -r1.226.2.35 *** _ctypes.c 3 Nov 2005 19:47:27 -0000 1.226.2.34 --- _ctypes.c 3 Nov 2005 20:04:12 -0000 1.226.2.35 *************** *** 3710,3713 **** --- 3710,3739 ---- }; + #if (PY_VERSION_HEX < 0x02040000) + /* Only in Python 2.4 and up */ + static PyObject * + PyTuple_Pack(int n, ...) + { + int i; + PyObject *o; + PyObject *result; + PyObject **items; + va_list vargs; + + va_start(vargs, n); + result = PyTuple_New(n); + if (result == NULL) + return NULL; + items = ((PyTupleObject *)result)->ob_item; + for (i = 0; i < n; i++) { + o = va_arg(vargs, PyObject *); + Py_INCREF(o); + items[i] = o; + } + va_end(vargs); + return result; + } + #endif + /* "%s(%s)" % (self.__class__.__name__, self.value) */ static PyObject * |
Update of /cvsroot/ctypes/ctypes/unittests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv5346 Removed Files: Tag: branch_1_0 test_win32.py test_variant.py test_values.py test_unicode.py test_structures.py test_struct_fields.py test_strings.py test_stringptr.py test_slicing.py test_returnfuncptrs.py test_repr.py test_refcounts.py test_random_things.py test_python_api.py test_prototypes.py test_posix.py test_pointers.py test_paramflags.py test_parameters.py test_numbers.py test_memfunctions.py test_macholib.py test_libc.py test_leaks.py test_keeprefs.py test_internals.py test_integers.py test_init.py test_incomplete.py test_functions.py test_funcptr.py test_comobject.py test_codegen.py test_checkretval.py test_cfuncs.py test_cast.py test_callbacks.py test_buffers.py test_bitfields.py test_arrays.py runtests.py benchmark.py bench.bat .cvsignore Log Message: Move tests into a ctypes.test package, and remove the unittests directory. --- test_variant.py DELETED --- --- test_functions.py DELETED --- --- test_values.py DELETED --- --- test_python_api.py DELETED --- --- test_libc.py DELETED --- --- test_refcounts.py DELETED --- --- test_cfuncs.py DELETED --- --- test_numbers.py DELETED --- --- test_macholib.py DELETED --- --- test_integers.py DELETED --- --- test_win32.py DELETED --- --- test_random_things.py DELETED --- --- test_bitfields.py DELETED --- --- test_keeprefs.py DELETED --- --- test_codegen.py DELETED --- --- test_incomplete.py DELETED --- --- test_funcptr.py DELETED --- --- bench.bat DELETED --- --- test_structures.py DELETED --- --- .cvsignore DELETED --- --- test_buffers.py DELETED --- --- test_prototypes.py DELETED --- --- benchmark.py DELETED --- --- test_callbacks.py DELETED --- --- runtests.py DELETED --- --- test_checkretval.py DELETED --- --- test_parameters.py DELETED --- --- test_returnfuncptrs.py DELETED --- --- test_slicing.py DELETED --- --- test_leaks.py DELETED --- --- test_pointers.py DELETED --- --- test_init.py DELETED --- --- test_strings.py DELETED --- --- test_unicode.py DELETED --- --- test_repr.py DELETED --- --- test_comobject.py DELETED --- --- test_internals.py DELETED --- --- test_stringptr.py DELETED --- --- test_paramflags.py DELETED --- --- test_cast.py DELETED --- --- test_arrays.py DELETED --- --- test_memfunctions.py DELETED --- --- test_struct_fields.py DELETED --- --- test_posix.py DELETED --- |
Update of /cvsroot/ctypes/ctypes/ctypes/test In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4798 Added Files: Tag: branch_1_0 test_win32.py test_variant.py test_values.py test_unicode.py test_structures.py test_struct_fields.py test_strings.py test_stringptr.py test_slicing.py test_simplesubclasses.py test_returnfuncptrs.py test_repr.py test_refcounts.py test_random_things.py test_python_api.py test_prototypes.py test_posix.py test_pointers.py test_paramflags.py test_parameters.py test_numbers.py test_memfunctions.py test_macholib.py test_libc.py test_leaks.py test_keeprefs.py test_internals.py test_integers.py test_init.py test_incomplete.py test_functions.py test_funcptr.py test_errcheck.py test_comobject.py test_codegen.py test_checkretval.py test_cfuncs.py test_cast.py test_callbacks.py test_buffers.py test_bitfields.py test_arrays.py runtests.py __init__.py .cvsignore Log Message: Move tests into a ctypes.test package. --- NEW FILE: test_variant.py --- import unittest, os from ctypes import * def get_refcnt(comptr): # return the COM reference count of a COM interface pointer if not comptr: return 0 comptr.AddRef() return comptr.Release() if os.name == "nt": class VariantTestCase(unittest.TestCase): def __init__(self, *args): # We cannot import these at module level, but want these to be # available in the global namespace global IUnknown, VARIANT, LoadTypeLibEx, DISPPARAMS, LoadRegTypeLib, GUID from ctypes.com import IUnknown, GUID from ctypes.com.automation import VARIANT, LoadTypeLibEx, DISPPARAMS, LoadRegTypeLib unittest.TestCase.__init__(self, *args) def test_com_refcounts(self): # typelib for Internet Explorer tlb = LoadRegTypeLib(GUID("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}"), 1, 1, 0) self.failUnlessEqual(get_refcnt(tlb), 1) p = POINTER(IUnknown)() tlb.QueryInterface(byref(IUnknown._iid_), byref(p)) self.failUnlessEqual(get_refcnt(tlb), 2) del p self.failUnlessEqual(get_refcnt(tlb), 1) def test_com_pointers(self): """Storing a COM interface pointer in a VARIANT increments the refcount, changing the variant to contain something else decrements it""" tlb = LoadRegTypeLib(GUID("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}"), 1, 1, 0) self.failUnlessEqual(get_refcnt(tlb), 1) v = VARIANT(tlb) self.failUnlessEqual(get_refcnt(tlb), 2) p = v.value self.failUnlessEqual(get_refcnt(tlb), 3) del p self.failUnlessEqual(get_refcnt(tlb), 2) v.value = None self.failUnlessEqual(get_refcnt(tlb), 1) def test_null_com_pointers(self): p = POINTER(IUnknown)() self.failUnlessEqual(get_refcnt(p), 0) v = VARIANT(p) self.failUnlessEqual(get_refcnt(p), 0) def test_dispparams(self): # DISPPARAMS is a complex structure, well worth testing. d = DISPPARAMS() d.rgvarg = (VARIANT * 3)() # XXX The following line fails, which is a real bug in ctypes: # SystemError: ...\Objects\listobject.c:105: bad argument to internal function ## d.rgvarg[0].value = 1 def test_pythonobjects(self): objects = [None, 42, 3.14, True, False, "abc", u"abc"] for x in objects: v = VARIANT(x) self.failUnlessEqual(x, v.value) ################################################################ if __name__ == '__main__': unittest.main() --- NEW FILE: test_functions.py --- """ Here is probably the place to write the docs, since the test-cases show how the type behave. Later... """ from ctypes import * import unittest try: WINFUNCTYPE except NameError: # fake to enable this test on Linux WINFUNCTYPE = CFUNCTYPE import _ctypes_test dll = CDLL(_ctypes_test.__file__) if sys.platform == "win32": windll = WinDLL(_ctypes_test.__file__) class FunctionTestCase(unittest.TestCase): def test_mro(self): # in Python 2.3, this raises TypeError: MRO conflict among bases classes, # in Python 2.2 it works. # # But in early versions of _ctypes.c, the result of tp_new # wasn't checked, and it even crashed Python. # Found by Greg Chapman. try: class X(object, Array): _length_ = 5 _type_ = "i" except TypeError: pass from _ctypes import _Pointer try: class X(object, _Pointer): pass except TypeError: pass from _ctypes import _SimpleCData try: class X(object, _SimpleCData): _type_ = "i" except TypeError: pass try: class X(object, Structure): _fields_ = [] except TypeError: pass def test_wchar_parm(self): try: c_wchar except NameError: return f = dll._testfunc_i_bhilfd f.argtypes = [c_byte, c_wchar, c_int, c_long, c_float, c_double] result = f(1, u"x", 3, 4, 5.0, 6.0) self.failUnlessEqual(result, 139) self.failUnlessEqual(type(result), int) def test_wchar_result(self): try: c_wchar except NameError: return f = dll._testfunc_i_bhilfd f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] f.restype = c_wchar result = f(0, 0, 0, 0, 0, 0) self.failUnlessEqual(result, u'\x00') def test_voidresult(self): f = dll._testfunc_v f.restype = None f.argtypes = [c_int, c_int, POINTER(c_int)] result = c_int() self.failUnlessEqual(None, f(1, 2, byref(result))) self.failUnlessEqual(result.value, 3) def test_intresult(self): f = dll._testfunc_i_bhilfd f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] result = f(1, 2, 3, 4, 5.0, 6.0) self.failUnlessEqual(result, 21) self.failUnlessEqual(type(result), int) result = f(-1, -2, -3, -4, -5.0, -6.0) self.failUnlessEqual(result, -21) self.failUnlessEqual(type(result), int) # If we declare the function to return a short, # is the high part split off? f.restype = c_short result = f(1, 2, 3, 4, 5.0, 6.0) self.failUnlessEqual(result, 21) self.failUnlessEqual(type(result), int) result = f(1, 2, 3, 0x10004, 5.0, 6.0) self.failUnlessEqual(result, 21) self.failUnlessEqual(type(result), int) # You cannot assing character format codes as restype any longer self.assertRaises(TypeError, setattr, f, "restype", "i") def test_floatresult(self): f = dll._testfunc_f_bhilfd f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] f.restype = c_float result = f(1, 2, 3, 4, 5.0, 6.0) self.failUnlessEqual(result, 21) self.failUnlessEqual(type(result), float) result = f(-1, -2, -3, -4, -5.0, -6.0) self.failUnlessEqual(result, -21) self.failUnlessEqual(type(result), float) def test_doubleresult(self): f = dll._testfunc_d_bhilfd f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] f.restype = c_double result = f(1, 2, 3, 4, 5.0, 6.0) self.failUnlessEqual(result, 21) self.failUnlessEqual(type(result), float) result = f(-1, -2, -3, -4, -5.0, -6.0) self.failUnlessEqual(result, -21) self.failUnlessEqual(type(result), float) def test_longlongresult(self): try: c_longlong except NameError: return f = dll._testfunc_q_bhilfd f.restype = c_longlong f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double] result = f(1, 2, 3, 4, 5.0, 6.0) self.failUnlessEqual(result, 21) f = dll._testfunc_q_bhilfdq f.restype = c_longlong f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double, c_longlong] result = f(1, 2, 3, 4, 5.0, 6.0, 21) self.failUnlessEqual(result, 42) def test_stringresult(self): f = dll._testfunc_p_p f.argtypes = None f.restype = c_char_p result = f("123") self.failUnlessEqual(result, "123") result = f(None) self.failUnlessEqual(result, None) def test_pointers(self): f = dll._testfunc_p_p f.restype = POINTER(c_int) f.argtypes = [POINTER(c_int)] # This only works if the value c_int(42) passed to the # function is still alive while the pointer (the result) is # used. v = c_int(42) self.failUnlessEqual(pointer(v).contents.value, 42) result = f(pointer(v)) self.failUnlessEqual(type(result), POINTER(c_int)) self.failUnlessEqual(result.contents.value, 42) # This on works... result = f(pointer(v)) self.failUnlessEqual(result.contents.value, v.value) p = pointer(c_int(99)) result = f(p) self.failUnlessEqual(result.contents.value, 99) arg = byref(v) result = f(arg) self.failIfEqual(result.contents, v.value) self.assertRaises(ArgumentError, f, byref(c_short(22))) # It is dangerous, however, because you don't control the lifetime # of the pointer: result = f(byref(c_int(99))) self.failIfEqual(result.contents, 99) def test_errors(self): f = dll._testfunc_p_p f.restype = c_int class X(Structure): _fields_ = [("y", c_int)] self.assertRaises(TypeError, f, X()) #cannot convert parameter ################################################################ def test_shorts(self): f = dll._testfunc_callback_i_if args = [] expected = [262144, 131072, 65536, 32768, 16384, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1] def callback(v): args.append(v) CallBack = CFUNCTYPE(c_int, c_int) cb = CallBack(callback) f(2**18, cb) self.failUnlessEqual(args, expected) ################################################################ def test_callbacks(self): f = dll._testfunc_callback_i_if f.restype = c_int MyCallback = CFUNCTYPE(c_int, c_int) def callback(value): #print "called back with", value return value cb = MyCallback(callback) result = f(-10, cb) self.failUnlessEqual(result, -18) # test with prototype f.argtypes = [c_int, MyCallback] cb = MyCallback(callback) result = f(-10, cb) self.failUnlessEqual(result, -18) AnotherCallback = WINFUNCTYPE(c_int, c_int, c_int, c_int, c_int) # check that the prototype works: we call f with wrong # argument types cb = AnotherCallback(callback) self.assertRaises(ArgumentError, f, -10, cb) def test_callbacks_2(self): # Can also use simple datatypes as argument type specifiers # for the callback function. # In this case the call receives an instance of that type f = dll._testfunc_callback_i_if f.restype = c_int MyCallback = CFUNCTYPE(c_int, c_int) f.argtypes = [c_int, MyCallback] def callback(value): #print "called back with", value self.failUnlessEqual(type(value), int) return value cb = MyCallback(callback) result = f(-10, cb) self.failUnlessEqual(result, -18) def test_longlong_callbacks(self): f = dll._testfunc_callback_q_qf f.restype = c_longlong MyCallback = CFUNCTYPE(c_longlong, c_longlong) f.argtypes = [c_longlong, MyCallback] def callback(value): self.failUnless(isinstance(value, (int, long))) return value & 0x7FFFFFFF cb = MyCallback(callback) self.failUnlessEqual(13577625587, f(1000000000000, cb)) def test_errors(self): self.assertRaises(AttributeError, getattr, dll, "_xxx_yyy") self.assertRaises(ValueError, c_int.in_dll, dll, "_xxx_yyy") def test_byval(self): class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] # without prototype ptin = POINT(1, 2) ptout = POINT() # EXPORT int _testfunc_byval(point in, point *pout) result = dll._testfunc_byval(ptin, byref(ptout)) got = result, ptout.x, ptout.y expected = 3, 1, 2 self.failUnlessEqual(got, expected) # with prototype ptin = POINT(101, 102) ptout = POINT() dll._testfunc_byval.argtypes = (POINT, POINTER(POINT)) dll._testfunc_byval.restype = c_int result = dll._testfunc_byval(ptin, byref(ptout)) got = result, ptout.x, ptout.y expected = 203, 101, 102 self.failUnlessEqual(got, expected) def test_struct_return_2H(self): class S2H(Structure): _fields_ = [("x", c_short), ("y", c_short)] dll.ret_2h_func.restype = S2H dll.ret_2h_func.argtypes = [S2H] inp = S2H(99, 88) s2h = dll.ret_2h_func(inp) self.failUnlessEqual((s2h.x, s2h.y), (99*2, 88*3)) if sys.platform == "win32": def test_struct_return_2H_stdcall(self): class S2H(Structure): _fields_ = [("x", c_short), ("y", c_short)] windll.s_ret_2h_func.restype = S2H windll.s_ret_2h_func.argtypes = [S2H] s2h = windll.s_ret_2h_func(S2H(99, 88)) self.failUnlessEqual((s2h.x, s2h.y), (99*2, 88*3)) def test_struct_return_8H(self): class S8I(Structure): _fields_ = [("a", c_int), ("b", c_int), ("c", c_int), ("d", c_int), ("e", c_int), ("f", c_int), ("g", c_int), ("h", c_int)] dll.ret_8i_func.restype = S8I dll.ret_8i_func.argtypes = [S8I] inp = S8I(9, 8, 7, 6, 5, 4, 3, 2) s8i = dll.ret_8i_func(inp) self.failUnlessEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h), (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9)) if sys.platform == "win32": def test_struct_return_8H_stdcall(self): class S8I(Structure): _fields_ = [("a", c_int), ("b", c_int), ("c", c_int), ("d", c_int), ("e", c_int), ("f", c_int), ("g", c_int), ("h", c_int)] windll.s_ret_8i_func.restype = S8I windll.s_ret_8i_func.argtypes = [S8I] inp = S8I(9, 8, 7, 6, 5, 4, 3, 2) s8i = windll.s_ret_8i_func(inp) self.failUnlessEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h), (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9)) if __name__ == '__main__': unittest.main() --- NEW FILE: test_values.py --- """ A testcase which accesses *values* in a dll. """ import unittest from ctypes import * def find_test_dll(): import _ctypes_test return _ctypes_test.__file__ class ValuesTestCase(unittest.TestCase): def test_an_integer(self): ctdll = CDLL(find_test_dll()) an_integer = c_int.in_dll(ctdll, "an_integer") x = an_integer.value self.failUnlessEqual(x, ctdll.get_an_integer()) an_integer.value *= 2 self.failUnlessEqual(x*2, ctdll.get_an_integer()) def test_undefined(self): ctdll = CDLL(find_test_dll()) self.assertRaises(ValueError, c_int.in_dll, ctdll, "Undefined_Symbol") import sys name = "python%s%s" % sys.version_info[:2] try: pydll = getattr(cdll, name) except: pass else: class Win_ValuesTestCase(unittest.TestCase): """This test only works when python itself is a dll/shared library""" def test_optimizeflag(self): # This test accesses the Py_OptimizeFlag intger, which is # exported by the Python dll. # It's value is set depending on the -O and -OO flags: # if not given, it is 0 and __debug__ is 1. # If -O is given, the flag is 1, for -OO it is 2. # docstrings are also removed in the latter case. opt = c_int.in_dll(pydll, "Py_OptimizeFlag").value if __debug__: self.failUnlessEqual(opt, 0) elif ValuesTestCase.__doc__ is not None: self.failUnlessEqual(opt, 1) else: self.failUnlessEqual(opt, 2) def test_frozentable(self): # Python exports a PyImport_FrozenModules symbol. This is a # pointer to an array of struct _frozen entries. The end of the # array is marked by an entry containing a NULL name and zero # size. # In standard Python, this table contains a __hello__ # module, and a __phello__ package containing a spam # module. class struct_frozen(Structure): _fields_ = [("name", c_char_p), ("code", POINTER(c_ubyte)), ("size", c_int)] FrozenTable = POINTER(struct_frozen) ft = FrozenTable.in_dll(pydll, "PyImport_FrozenModules") # ft is a pointer to the struct_frozen entries: items = [] for entry in ft: # This is dangerous. We *can* iterate over a pointer, but # the loop will not terminate (maybe with an access # violation;-) because the pointer instance has no size. if entry.name is None: break items.append((entry.name, entry.size)) import sys if sys.version_info[:2] >= (2, 3): expected = [("__hello__", 104), ("__phello__", -104), ("__phello__.spam", 104)] else: expected = [("__hello__", 100), ("__phello__", -100), ("__phello__.spam", 100)] self.failUnlessEqual(items, expected) from ctypes import _pointer_type_cache del _pointer_type_cache[struct_frozen] def test_undefined(self): self.assertRaises(ValueError, c_int.in_dll, pydll, "Undefined_Symbol") if __name__ == '__main__': unittest.main() --- NEW FILE: test_python_api.py --- from ctypes import * import unittest, sys ################################################################ # This section should be moved into ctypes\__init__.py, when it's ready. from _ctypes import PyObj_FromPtr ################################################################ from sys import getrefcount as grc class PythonAPITestCase(unittest.TestCase): def test_PyString_FromStringAndSize(self): PyString_FromStringAndSize = pythonapi.PyString_FromStringAndSize PyString_FromStringAndSize.restype = py_object PyString_FromStringAndSize.argtypes = c_char_p, c_int self.failUnlessEqual(PyString_FromStringAndSize("abcdefghi", 3), "abc") def test_PyString_FromString(self): pythonapi.PyString_FromString.restype = py_object pythonapi.PyString_FromString.argtypes = (c_char_p,) s = "abc" refcnt = grc(s) pyob = pythonapi.PyString_FromString(s) self.failUnlessEqual(grc(s), refcnt) self.failUnlessEqual(s, pyob) del pyob self.failUnlessEqual(grc(s), refcnt) def test_PyInt_Long(self): ref42 = grc(42) pythonapi.PyInt_FromLong.restype = py_object self.failUnlessEqual(pythonapi.PyInt_FromLong(42), 42) self.failUnlessEqual(grc(42), ref42) pythonapi.PyInt_AsLong.argtypes = (py_object,) pythonapi.PyInt_AsLong.restype = c_long res = pythonapi.PyInt_AsLong(42) self.failUnlessEqual(grc(res), ref42 + 1) del res self.failUnlessEqual(grc(42), ref42) def test_PyObj_FromPtr(self): s = "abc def ghi jkl" ref = grc(s) # id(python-object) is the address pyobj = PyObj_FromPtr(id(s)) self.failUnless(s is pyobj) self.failUnlessEqual(grc(s), ref + 1) del pyobj self.failUnlessEqual(grc(s), ref) def test_PyOS_snprintf(self): PyOS_snprintf = pythonapi.PyOS_snprintf PyOS_snprintf.argtypes = POINTER(c_char), c_int, c_char_p buf = c_buffer(256) PyOS_snprintf(buf, sizeof(buf), "Hello from %s", "ctypes") self.failUnlessEqual(buf.value, "Hello from ctypes") PyOS_snprintf(buf, sizeof(buf), "Hello from %s", "ctypes", 1, 2, 3) self.failUnlessEqual(buf.value, "Hello from ctypes") # not enough arguments self.failUnlessRaises(TypeError, PyOS_snprintf, buf) if __name__ == "__main__": unittest.main() --- NEW FILE: test_libc.py --- import os import sys import unittest from ctypes import * from ctypes.util import find_library from ctypes.decorators import cdecl, name_library # specify which libraries the decorator has to load. Normally, one # would use ful so-names to specify exact the library we want. if os.name == "nt": name_library("libc", "msvcrt") name_library("libm", "msvcrt") elif os.name == "darwin": name_library("libc", find_library("c")) name_library("libm", find_library("m")) else: name_library("libc", "libc.so.6") name_library("libm", find_library("m")) # load libraries with cdll magic. I still don't know how to find # 'libc.so.6' from 'c' on linux, otherwise this could be a lot nicer. if os.name == "nt": libm = libc = cdll.msvcrt elif sys.platform == "darwin": libc = cdll.c libm = cdll.m else: libc = CDLL("libc.so.6") libm = cdll.m class LibTest(unittest.TestCase): def test_sqrt(self): libm.sqrt.argtypes = c_double, libm.sqrt.restype = c_double self.failUnlessEqual(libm.sqrt(4.0), 2.0) import math self.failUnlessEqual(libm.sqrt(2.0), math.sqrt(2.0)) def test_cdecl_decorator(self): # @ cdecl(c_double, "libm", [c_double]) def sqrt(value): return sqrt._api_(value) # Oh well, compatibility with Python 2.3 sqrt = cdecl(c_double, "libm", [c_double]) (sqrt) self.failUnlessEqual(sqrt(4.0), 2.0) def test_qsort(self): comparefunc = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_char)) libc.qsort.argtypes = c_void_p, c_int, c_int, comparefunc libc.qsort.restype = None def sort(a, b): return cmp(a[0], b[0]) chars = create_string_buffer("spam, spam, and spam") libc.qsort(chars, len(chars)-1, sizeof(c_char), comparefunc(sort)) self.failUnlessEqual(chars.raw, " ,,aaaadmmmnpppsss\x00") def test_qsort_decorator(self): from ctypes.decorators import cdecl, name_library CMPFUNC = CFUNCTYPE(c_int, c_void_p, c_void_p) #@ cdecl(None, "libc", [c_void_p, c_int, c_int, CMPFUNC]) def qsort(sequence, cmp_func): itemsize = sizeof(sequence) / len(sequence) qsort._api_(sequence, len(sequence), itemsize, CMPFUNC(cmp_func)) qsort = cdecl(None, "libc", [c_void_p, c_int, c_int, CMPFUNC])(qsort) def sortfunc(a, b): a = cast(a, POINTER(c_int)) b = cast(b, POINTER(c_int)) return cmp(a[0], b[0]) ints = (c_int * 9)(1, 3, 5, 7, 9, 8, 6, 4, 2) qsort(ints, sortfunc) self.failUnlessEqual(ints[:], [1, 2, 3, 4, 5, 6, 7, 8, 9]) if __name__ == "__main__": unittest.main() --- NEW FILE: test_refcounts.py --- import unittest import ctypes import gc MyCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int) OtherCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_ulonglong) import _ctypes_test dll = ctypes.CDLL(_ctypes_test.__file__) class RefcountTestCase(unittest.TestCase): def test_1(self): from sys import getrefcount as grc f = dll._testfunc_callback_i_if f.restype = ctypes.c_int f.argtypes = [ctypes.c_int, MyCallback] def callback(value): #print "called back with", value return value self.failUnlessEqual(grc(callback), 2) cb = MyCallback(callback) self.failUnless(grc(callback) > 2) result = f(-10, cb) self.failUnlessEqual(result, -18) cb = None gc.collect() self.failUnlessEqual(grc(callback), 2) def test_refcount(self): from sys import getrefcount as grc def func(*args): pass # this is the standard refcount for func self.failUnlessEqual(grc(func), 2) # the CFuncPtr instance holds atr least one refcount on func: f = OtherCallback(func) self.failUnless(grc(func) > 2) # and may release it again del f self.failUnless(grc(func) >= 2) # but now it must be gone gc.collect() self.failUnless(grc(func) == 2) class X(ctypes.Structure): _fields_ = [("a", OtherCallback)] x = X() x.a = OtherCallback(func) # the CFuncPtr instance holds atr least one refcount on func: self.failUnless(grc(func) > 2) # and may release it again del x self.failUnless(grc(func) >= 2) # and now it must be gone again gc.collect() self.failUnlessEqual(grc(func), 2) f = OtherCallback(func) # the CFuncPtr instance holds atr least one refcount on func: self.failUnless(grc(func) > 2) # create a cycle f.cycle = f del f gc.collect() self.failUnlessEqual(grc(func), 2) class AnotherLeak(unittest.TestCase): def test_callback(self): import sys proto = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int) def func(a, b): return a * b * 2 f = proto(func) a = sys.getrefcount(ctypes.c_int) f(1, 2) self.failUnlessEqual(sys.getrefcount(ctypes.c_int), a) if __name__ == '__main__': unittest.main() --- NEW FILE: test_cfuncs.py --- # A lot of failures in these tests on Mac OS X. # Byte order related? import unittest from ctypes import * import _ctypes_test class CFunctions(unittest.TestCase): _dll = CDLL(_ctypes_test.__file__) def S(self): return c_longlong.in_dll(self._dll, "last_tf_arg_s").value def U(self): return c_ulonglong.in_dll(self._dll, "last_tf_arg_u").value def test_byte(self): self._dll.tf_b.restype = c_byte self._dll.tf_b.argtypes = (c_byte,) self.failUnlessEqual(self._dll.tf_b(-126), -42) self.failUnlessEqual(self.S(), -126) def test_byte_plus(self): self._dll.tf_bb.restype = c_byte self._dll.tf_bb.argtypes = (c_byte, c_byte) self.failUnlessEqual(self._dll.tf_bb(0, -126), -42) self.failUnlessEqual(self.S(), -126) def test_ubyte(self): self._dll.tf_B.restype = c_ubyte self._dll.tf_B.argtypes = (c_ubyte,) self.failUnlessEqual(self._dll.tf_B(255), 85) self.failUnlessEqual(self.U(), 255) def test_ubyte_plus(self): self._dll.tf_bB.restype = c_ubyte self._dll.tf_bB.argtypes = (c_byte, c_ubyte) self.failUnlessEqual(self._dll.tf_bB(0, 255), 85) self.failUnlessEqual(self.U(), 255) def test_short(self): self._dll.tf_h.restype = c_short self.failUnlessEqual(self._dll.tf_h(-32766), -10922) self.failUnlessEqual(self.S(), -32766) def test_short_plus(self): self._dll.tf_bh.restype = c_short self.failUnlessEqual(self._dll.tf_bh(0, -32766), -10922) self.failUnlessEqual(self.S(), -32766) def test_ushort(self): self._dll.tf_H.restype = c_ushort self.failUnlessEqual(self._dll.tf_H(65535), 21845) self.failUnlessEqual(self.U(), 65535) def test_ushort_plus(self): self._dll.tf_bH.restype = c_ushort self.failUnlessEqual(self._dll.tf_bH(0, 65535), 21845) self.failUnlessEqual(self.U(), 65535) def test_int(self): self._dll.tf_i.restype = c_int self.failUnlessEqual(self._dll.tf_i(-2147483646), -715827882) self.failUnlessEqual(self.S(), -2147483646) def test_int_plus(self): self._dll.tf_bi.restype = c_int self.failUnlessEqual(self._dll.tf_bi(0, -2147483646), -715827882) self.failUnlessEqual(self.S(), -2147483646) def test_uint(self): self._dll.tf_I.restype = c_uint self.failUnlessEqual(self._dll.tf_I(4294967295), 1431655765) self.failUnlessEqual(self.U(), 4294967295) def test_uint_plus(self): self._dll.tf_bI.restype = c_uint self.failUnlessEqual(self._dll.tf_bI(0, 4294967295), 1431655765) self.failUnlessEqual(self.U(), 4294967295) def test_long(self): self._dll.tf_l.restype = c_long self._dll.tf_l.argtypes = (c_long,) self.failUnlessEqual(self._dll.tf_l(-2147483646), -715827882) self.failUnlessEqual(self.S(), -2147483646) def test_long_plus(self): self._dll.tf_bl.restype = c_long self._dll.tf_bl.argtypes = (c_byte, c_long) self.failUnlessEqual(self._dll.tf_bl(0, -2147483646), -715827882) self.failUnlessEqual(self.S(), -2147483646) def test_ulong(self): self._dll.tf_L.restype = c_ulong self.failUnlessEqual(self._dll.tf_L(4294967295), 1431655765) self.failUnlessEqual(self.U(), 4294967295) def test_ulong_plus(self): self._dll.tf_bL.restype = c_ulong self.failUnlessEqual(self._dll.tf_bL(0, 4294967295), 1431655765) self.failUnlessEqual(self.U(), 4294967295) def test_longlong(self): self._dll.tf_q.restype = c_longlong self._dll.tf_q.argtypes = (c_longlong, ) self.failUnlessEqual(self._dll.tf_q(-9223372036854775806), -3074457345618258602) self.failUnlessEqual(self.S(), -9223372036854775806) def test_longlong_plus(self): self._dll.tf_bq.restype = c_longlong self._dll.tf_bq.argtypes = (c_byte, c_longlong) self.failUnlessEqual(self._dll.tf_bq(0, -9223372036854775806), -3074457345618258602) self.failUnlessEqual(self.S(), -9223372036854775806) def test_ulonglong(self): self._dll.tf_Q.restype = c_ulonglong self._dll.tf_Q.argtypes = (c_ulonglong, ) self.failUnlessEqual(self._dll.tf_Q(18446744073709551615), 6148914691236517205) self.failUnlessEqual(self.U(), 18446744073709551615) def test_ulonglong_plus(self): self._dll.tf_bQ.restype = c_ulonglong self._dll.tf_bQ.argtypes = (c_byte, c_ulonglong) self.failUnlessEqual(self._dll.tf_bQ(0, 18446744073709551615), 6148914691236517205) self.failUnlessEqual(self.U(), 18446744073709551615) def test_float(self): self._dll.tf_f.restype = c_float self._dll.tf_f.argtypes = (c_float,) self.failUnlessEqual(self._dll.tf_f(-42.), -14.) self.failUnlessEqual(self.S(), -42) def test_float_plus(self): self._dll.tf_bf.restype = c_float self._dll.tf_bf.argtypes = (c_byte, c_float) self.failUnlessEqual(self._dll.tf_bf(0, -42.), -14.) self.failUnlessEqual(self.S(), -42) def test_double(self): self._dll.tf_d.restype = c_double self._dll.tf_d.argtypes = (c_double,) self.failUnlessEqual(self._dll.tf_d(42.), 14.) self.failUnlessEqual(self.S(), 42) def test_double_plus(self): self._dll.tf_bd.restype = c_double self._dll.tf_bd.argtypes = (c_byte, c_double) self.failUnlessEqual(self._dll.tf_bd(0, 42.), 14.) self.failUnlessEqual(self.S(), 42) def test_callwithresult(self): def process_result(result): return result * 2 self._dll.tf_i.restype = process_result self._dll.tf_i.argtypes = (c_int,) self.failUnlessEqual(self._dll.tf_i(42), 28) self.failUnlessEqual(self.S(), 42) self.failUnlessEqual(self._dll.tf_i(-42), -28) self.failUnlessEqual(self.S(), -42) def test_void(self): self._dll.tv_i.restype = None self._dll.tv_i.argtypes = (c_int,) self.failUnlessEqual(self._dll.tv_i(42), None) self.failUnlessEqual(self.S(), 42) self.failUnlessEqual(self._dll.tv_i(-42), None) self.failUnlessEqual(self.S(), -42) # The following repeates the above tests with stdcall functions (where # they are available) try: WinDLL except NameError: pass else: class stdcall_dll(WinDLL): def __getattr__(self, name): if name[:2] == '__' and name[-2:] == '__': raise AttributeError, name func = self._StdcallFuncPtr("s_" + name, self) setattr(self, name, func) return func class stdcallCFunctions(CFunctions): _dll = stdcall_dll(_ctypes_test.__file__) pass if __name__ == '__main__': unittest.main() --- NEW FILE: test_numbers.py --- from ctypes import * import unittest import sys, struct def valid_ranges(*types): # given a sequence of numeric types, collect their _type_ # attribute, which is a single format character compatible with # the struct module, use the struct module to calculate the # minimum and maximum value allowed for this format. # Returns a list of (min, max) values. result = [] for t in types: fmt = t._type_ size = struct.calcsize(fmt) a = struct.unpack(fmt, ("\x00"*32)[:size])[0] b = struct.unpack(fmt, ("\xFF"*32)[:size])[0] c = struct.unpack(fmt, ("\x7F"+"\x00"*32)[:size])[0] d = struct.unpack(fmt, ("\x80"+"\xFF"*32)[:size])[0] result.append((min(a, b, c, d), max(a, b, c, d))) return result ArgType = type(c_int(0)._as_parameter_) unsigned_types = [c_ubyte, c_ushort, c_uint, c_ulong] signed_types = [c_byte, c_short, c_int, c_long, c_longlong] float_types = [c_double, c_float] try: c_ulonglong c_longlong except NameError: pass else: unsigned_types.append(c_ulonglong) signed_types.append(c_longlong) unsigned_ranges = valid_ranges(*unsigned_types) signed_ranges = valid_ranges(*signed_types) ################################################################ class NumberTestCase(unittest.TestCase): def test_default_init(self): # default values are set to zero for t in signed_types + unsigned_types + float_types: self.failUnlessEqual(t().value, 0) def test_unsigned_values(self): # the value given to the constructor is available # as the 'value' attribute for t, (l, h) in zip(unsigned_types, unsigned_ranges): self.failUnlessEqual(t(l).value, l) self.failUnlessEqual(t(h).value, h) def test_signed_values(self): # see above for t, (l, h) in zip(signed_types, signed_ranges): self.failUnlessEqual(t(l).value, l) self.failUnlessEqual(t(h).value, h) def test_typeerror(self): # Only numbers are allowed in the contructor, # otherwise TypeError is raised for t in signed_types + unsigned_types + float_types: self.assertRaises(TypeError, t, "") self.assertRaises(TypeError, t, None) ## def test_valid_ranges(self): ## # invalid values of the correct type ## # raise ValueError (not OverflowError) ## for t, (l, h) in zip(unsigned_types, unsigned_ranges): ## self.assertRaises(ValueError, t, l-1) ## self.assertRaises(ValueError, t, h+1) def test_from_param(self): # the from_param class method attribute always # returns PyCArgObject instances for t in signed_types + unsigned_types + float_types: self.failUnlessEqual(ArgType, type(t.from_param(0))) def test_as_parameter(self): # The _as_parameter_ property must also # be a PyCArgObject instance for t in signed_types + unsigned_types + float_types: parm = t()._as_parameter_ self.failUnlessEqual(ArgType, type(parm)) # _as_parameter_ is readonly! # # Python 2.3 and 2.4 raise a TypeError when trying to set # a readonly attribute, 2.5 raises an AttributeError. self.assertRaises((AttributeError, TypeError), setattr, t(), "_as_parameter_", None) def test_byref(self): # calling byref returns also a PyCArgObject instance for t in signed_types + unsigned_types + float_types: parm = byref(t()) self.failUnlessEqual(ArgType, type(parm)) def test_floats(self): # c_float and c_double can be created from # Python int, long and float for t in float_types: self.failUnlessEqual(t(2.0).value, 2.0) self.failUnlessEqual(t(2).value, 2.0) self.failUnlessEqual(t(2L).value, 2.0) def test_integers(self): # integers cannot be constructed from floats for t in signed_types + unsigned_types: self.assertRaises(TypeError, t, 3.14) def test_sizes(self): for t in signed_types + unsigned_types + float_types: size = struct.calcsize(t._type_) # sizeof of the type... self.failUnlessEqual(sizeof(t), size) # and sizeof of an instance self.failUnlessEqual(sizeof(t()), size) def test_alignments(self): for t in signed_types + unsigned_types + float_types: code = t._type_ # the typecode align = struct.calcsize("c%c" % code) - struct.calcsize(code) # alignment of the type... self.failUnlessEqual((code, alignment(t)), (code, align)) # and alignment of an instance self.failUnlessEqual((code, alignment(t())), (code, align)) def test_int_from_address(self): from array import array for t in signed_types + unsigned_types: # the array module doesn't suppport all format codes # (no 'q' or 'Q') try: array(t._type_) except ValueError: continue a = array(t._type_, [100]) # v now is an integer at an 'external' memory location v = t.from_address(a.buffer_info()[0]) self.failUnlessEqual(v.value, a[0]) self.failUnlessEqual(type(v), t) # changing the value at the memory location changes v's value also a[0] = 42 self.failUnlessEqual(v.value, a[0]) def test_float_from_address(self): from array import array for t in float_types: a = array(t._type_, [3.14]) v = t.from_address(a.buffer_info()[0]) self.failUnlessEqual(v.value, a[0]) self.failUnless(type(v) is t) a[0] = 2.3456e17 self.failUnlessEqual(v.value, a[0]) self.failUnless(type(v) is t) def test_char_from_address(self): from ctypes import c_char from array import array a = array('c', 'x') v = c_char.from_address(a.buffer_info()[0]) self.failUnlessEqual(v.value, a[0]) self.failUnless(type(v) is c_char) a[0] = '?' self.failUnlessEqual(v.value, a[0]) def test_init(self): # c_int() can be initialized from Python's int, and c_int. # Not from c_long or so, which seems strange, abd should # probably be changed: self.assertRaises(TypeError, c_int, c_long(42)) ## def test_perf(self): ## check_perf() from ctypes import _SimpleCData class c_int_S(_SimpleCData): _type_ = "i" __slots__ = [] def run_test(rep, msg, func, arg=None): ## items = [None] * rep items = range(rep) from time import clock if arg is not None: start = clock() for i in items: func(arg); func(arg); func(arg); func(arg); func(arg) stop = clock() else: start = clock() for i in items: func(); func(); func(); func(); func() stop = clock() print "%15s: %.2f us" % (msg, ((stop-start)*1e6/5/rep)) def check_perf(): # Construct 5 objects from ctypes import c_int REP = 200000 run_test(REP, "int()", int) run_test(REP, "int(999)", int) run_test(REP, "c_int()", c_int) run_test(REP, "c_int(999)", c_int) run_test(REP, "c_int_S()", c_int_S) run_test(REP, "c_int_S(999)", c_int_S) # Python 2.3 -OO, win2k, P4 700 MHz: # # int(): 0.87 us # int(999): 0.87 us # c_int(): 3.35 us # c_int(999): 3.34 us # c_int_S(): 3.23 us # c_int_S(999): 3.24 us # Python 2.2 -OO, win2k, P4 700 MHz: # # int(): 0.89 us # int(999): 0.89 us # c_int(): 9.99 us # c_int(999): 10.02 us # c_int_S(): 9.87 us # c_int_S(999): 9.85 us if __name__ == '__main__': ## check_perf() unittest.main() --- NEW FILE: test_macholib.py --- import os import sys import unittest # Bob Ippolito: """ Ok.. the code to find the filename for __getattr__ should look something like: import os from macholib.dyld import dyld_find def find_lib(name): possible = ['lib'+name+'.dylib', name+'.dylib', name+'.framework/'+name] for dylib in possible: try: return os.path.realpath(dyld_find(dylib)) except ValueError: pass raise ValueError, "%s not found" % (name,) It'll have output like this: >>> find_lib('pthread') '/usr/lib/libSystem.B.dylib' >>> find_lib('z') '/usr/lib/libz.1.dylib' >>> find_lib('IOKit') '/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit' -bob """ from ctypes.macholib.dyld import dyld_find def find_lib(name): possible = ['lib'+name+'.dylib', name+'.dylib', name+'.framework/'+name] for dylib in possible: try: return os.path.realpath(dyld_find(dylib)) except ValueError: pass raise ValueError, "%s not found" % (name,) class MachOTest(unittest.TestCase): if sys.platform == "darwin": def test_find(self): self.failUnlessEqual(find_lib('pthread'), '/usr/lib/libSystem.B.dylib') result = find_lib('z') self.failUnless(result.startswith('/usr/lib/libz.1')) self.failUnless(result.endswith('.dylib')) self.failUnlessEqual(find_lib('IOKit'), '/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit') if __name__ == "__main__": unittest.main() --- NEW FILE: test_integers.py --- # superseeded by test_numbers.py import unittest if __name__ == '__main__': unittest.main() --- NEW FILE: test_win32.py --- # Windows specific tests from ctypes import * import unittest, sys def find_test_dll(): import _ctypes_test return _ctypes_test.__file__ if sys.platform == "win32": class WindowsTestCase(unittest.TestCase): def test_callconv_1(self): # Testing stdcall function IsWindow = windll.user32.IsWindow # ValueError: Procedure probably called with not enough arguments (4 bytes missing) self.assertRaises(ValueError, IsWindow) # This one should succeeed... self.failUnlessEqual(0, IsWindow(0)) # ValueError: Procedure probably called with too many arguments (8 bytes in excess) self.assertRaises(ValueError, IsWindow, 0, 0, 0) def test_callconv_2(self): # Calling stdcall function as cdecl IsWindow = cdll.user32.IsWindow # ValueError: Procedure called with not enough arguments (4 bytes missing) # or wrong calling convention self.assertRaises(ValueError, IsWindow, None) def test_SEH(self): # Call functions with invalid arguments, and make sure that access violations # are trapped and raise an exception. # # Normally, in a debug build of the _ctypes extension # module, exceptions are not trapped, so we can only run # this test in a release build. import sys if not hasattr(sys, "getobjects"): self.assertRaises(WindowsError, windll.kernel32.GetModuleHandleA, 32) class Structures(unittest.TestCase): def test_struct_by_value(self): class POINT(Structure): _fields_ = [("x", c_long), ("y", c_long)] class RECT(Structure): _fields_ = [("left", c_long), ("top", c_long), ("right", c_long), ("bottom", c_long)] dll = CDLL(find_test_dll()) pt = POINT(10, 10) rect = RECT(0, 0, 20, 20) self.failUnlessEqual(1, dll.PointInRect(byref(rect), pt)) if __name__ == '__main__': unittest.main() --- NEW FILE: test_random_things.py --- from ctypes import * import unittest, sys def callback_func(arg): 42 / arg raise ValueError, arg if sys.platform == "win32": class call_function_TestCase(unittest.TestCase): # _ctypes.call_function is deprecated and private, but used by # Gary Bishp's readline module. If we have it, we must test it as well. def test(self): from _ctypes import call_function hdll = windll.kernel32.LoadLibraryA("kernel32") funcaddr = windll.kernel32.GetProcAddress(hdll, "GetModuleHandleA") self.failUnlessEqual(call_function(funcaddr, (None,)), windll.kernel32.GetModuleHandleA(None)) class CallbackTracbackTestCase(unittest.TestCase): # When an exception is raised in a ctypes callback function, the C # code prints a traceback. # # This test makes sure the exception types *and* the exception # value is printed correctly. # # Changed in 0.9.3: No longer is '(in callback)' prepended to the # error message - instead a additional frame for the C code is # created, then a full traceback printed. When SystemExit is # raised in a callback function, the interpreter exits. def capture_stderr(self, func, *args, **kw): # helper - call function 'func', and return the captured stderr import StringIO old_stderr = sys.stderr logger = sys.stderr = StringIO.StringIO() try: func(*args, **kw) finally: sys.stderr = old_stderr return logger.getvalue() def test_ValueError(self): cb = CFUNCTYPE(c_int, c_int)(callback_func) out = self.capture_stderr(cb, 42) self.failUnlessEqual(out.splitlines()[-1], "ValueError: 42") def test_IntegerDivisionError(self): cb = CFUNCTYPE(c_int, c_int)(callback_func) out = self.capture_stderr(cb, 0) self.failUnlessEqual(out.splitlines()[-1], "ZeroDivisionError: " "integer division or modulo by zero") def test_FloatDivisionError(self): cb = CFUNCTYPE(c_int, c_double)(callback_func) out = self.capture_stderr(cb, 0.0) self.failUnlessEqual(out.splitlines()[-1], "ZeroDivisionError: " "float division") def test_TypeErrorDivisionError(self): cb = CFUNCTYPE(c_int, c_char_p)(callback_func) out = self.capture_stderr(cb, "spam") self.failUnlessEqual(out.splitlines()[-1], "TypeError: " "unsupported operand type(s) for /: 'int' and 'str'") if __name__ == '__main__': unittest.main() --- NEW FILE: test_bitfields.py --- from ctypes import * import unittest import sys import ctypes import _ctypes_test class BITS(Structure): _fields_ = [("A", c_int, 1), ("B", c_int, 2), ("C", c_int, 3), ("D", c_int, 4), ("E", c_int, 5), ("F", c_int, 6), ("G", c_int, 7), ("H", c_int, 8), ("I", c_int, 9), ("M", c_short, 1), ("N", c_short, 2), ("O", c_short, 3), ("P", c_short, 4), ("Q", c_short, 5), ("R", c_short, 6), ("S", c_short, 7)] func = CDLL(_ctypes_test.__file__).unpack_bitfields func.argtypes = POINTER(BITS), c_char ##for n in "ABCDEFGHIMNOPQRS": ## print n, hex(getattr(BITS, n).size), getattr(BITS, n).offset class C_Test(unittest.TestCase): def test_ints(self): for i in range(512): for name in "ABCDEFGHI": b = BITS() setattr(b, name, i) self.failUnlessEqual((name, i, getattr(b, name)), (name, i, func(byref(b), name))) def test_shorts(self): for i in range(256): for name in "MNOPQRS": b = BITS() setattr(b, name, i) self.failUnlessEqual((name, i, getattr(b, name)), (name, i, func(byref(b), name))) signed_int_types = (c_byte, c_short, c_int, c_long, c_longlong) unsigned_int_types = (c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong) int_types = unsigned_int_types + signed_int_types class BitFieldTest(unittest.TestCase): def test_longlong(self): class X(Structure): _fields_ = [("a", c_longlong, 1), ("b", c_longlong, 62), ("c", c_longlong, 1)] self.failUnlessEqual(sizeof(X), sizeof(c_longlong)) x = X() x.a, x.b, x.c = -1, 7, -1 self.failUnlessEqual((x.a, x.b, x.c), (-1, 7, -1)) def test_ulonglong(self): class X(Structure): _fields_ = [("a", c_ulonglong, 1), ("b", c_ulonglong, 62), ("c", c_ulonglong, 1)] self.failUnlessEqual(sizeof(X), sizeof(c_longlong)) x = X() self.failUnlessEqual((x.a, x.b, x.c), (0, 0, 0)) x.a, x.b, x.c = 7, 7, 7 self.failUnlessEqual((x.a, x.b, x.c), (1, 7, 1)) def test_signed(self): for c_typ in signed_int_types: class X(Structure): _fields_ = [("dummy", c_typ), ("a", c_typ, 3), ("b", c_typ, 3), ("c", c_typ, 1)] self.failUnlessEqual(sizeof(X), sizeof(c_typ)*2) x = X() self.failUnlessEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 0, 0)) x.a = -1 self.failUnlessEqual((c_typ, x.a, x.b, x.c), (c_typ, -1, 0, 0)) x.a, x.b = 0, -1 self.failUnlessEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, -1, 0)) def test_unsigned(self): for c_typ in unsigned_int_types: class X(Structure): _fields_ = [("a", c_typ, 3), ("b", c_typ, 3), ("c", c_typ, 1)] self.failUnlessEqual(sizeof(X), sizeof(c_typ)) x = X() self.failUnlessEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 0, 0)) x.a = -1 self.failUnlessEqual((c_typ, x.a, x.b, x.c), (c_typ, 7, 0, 0)) x.a, x.b = 0, -1 self.failUnlessEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 7, 0)) def fail_fields(self, *fields): return self.get_except(type(Structure), "X", (), {"_fields_": fields}) def test_nonint_types(self): # bit fields are not allowed on non-integer types. result = self.fail_fields(("a", c_char_p, 1)) self.failUnlessEqual(result, (TypeError, 'bit fields not allowed for type c_char_p')) result = self.fail_fields(("a", c_void_p, 1)) self.failUnlessEqual(result, (TypeError, 'bit fields not allowed for type c_void_p')) if c_int != c_long: result = self.fail_fields(("a", POINTER(c_int), 1)) self.failUnlessEqual(result, (TypeError, 'bit fields not allowed for type LP_c_int')) result = self.fail_fields(("a", c_char, 1)) self.failUnlessEqual(result, (TypeError, 'bit fields not allowed for type c_char')) try: c_wchar except NameError: pass else: result = self.fail_fields(("a", c_wchar, 1)) self.failUnlessEqual(result, (TypeError, 'bit fields not allowed for type c_wchar')) class Dummy(Structure): _fields_ = [] result = self.fail_fields(("a", Dummy, 1)) self.failUnlessEqual(result, (TypeError, 'bit fields not allowed for type Dummy')) def test_single_bitfield_size(self): for c_typ in int_types: result = self.fail_fields(("a", c_typ, -1)) self.failUnlessEqual(result, (ValueError, 'number of bits invalid for bit field')) result = self.fail_fields(("a", c_typ, 0)) self.failUnlessEqual(result, (ValueError, 'number of bits invalid for bit field')) class X(Structure): _fields_ = [("a", c_typ, 1)] self.failUnlessEqual(sizeof(X), sizeof(c_typ)) class X(Structure): _fields_ = [("a", c_typ, sizeof(c_typ)*8)] self.failUnlessEqual(sizeof(X), sizeof(c_typ)) result = self.fail_fields(("a", c_typ, sizeof(c_typ)*8 + 1)) self.failUnlessEqual(result, (ValueError, 'number of bits invalid for bit field')) def test_multi_bitfields_size(self): class X(Structure): _fields_ = [("a", c_short, 1), ("b", c_short, 14), ("c", c_short, 1)] self.failUnlessEqual(sizeof(X), sizeof(c_short)) class X(Structure): _fields_ = [("a", c_short, 1), ("a1", c_short), ("b", c_short, 14), ("c", c_short, 1)] self.failUnlessEqual(sizeof(X), sizeof(c_short)*3) self.failUnlessEqual(X.a.offset, 0) self.failUnlessEqual(X.a1.offset, sizeof(c_short)) self.failUnlessEqual(X.b.offset, sizeof(c_short)*2) self.failUnlessEqual(X.c.offset, sizeof(c_short)*2) class X(Structure): _fields_ = [("a", c_short, 3), ("b", c_short, 14), ("c", c_short, 14)] self.failUnlessEqual(sizeof(X), sizeof(c_short)*3) self.failUnlessEqual(X.a.offset, sizeof(c_short)*0) self.failUnlessEqual(X.b.offset, sizeof(c_short)*1) self.failUnlessEqual(X.c.offset, sizeof(c_short)*2) def get_except(self, func, *args, **kw): try: func(*args, **kw) except Exception, detail: return detail.__class__, str(detail) def test_mixed_1(self): class X(Structure): _fields_ = [("a", c_byte, 4), ("b", c_int, 4)] if sys.platform == "win32": self.failUnlessEqual(sizeof(X), sizeof(c_int)*2) else: self.failUnlessEqual(sizeof(X), sizeof(c_int)) def test_mixed_2(self): class X(Structure): _fields_ = [("a", c_byte, 4), ("b", c_int, 32)] self.failUnlessEqual(sizeof(X), sizeof(c_int)*2) def test_mixed_3(self): class X(Structure): _fields_ = [("a", c_byte, 4), ("b", c_ubyte, 4)] self.failUnlessEqual(sizeof(X), sizeof(c_byte)) if __name__ == "__main__": unittest.main() --- NEW FILE: test_keeprefs.py --- from ctypes import * import unittest class SimpleTestCase(unittest.TestCase): def test_cint(self): x = c_int() self.assertEquals(x._objects, None) x.value = 42 self.assertEquals(x._objects, None) x = c_int(99) self.assertEquals(x._objects, None) def test_ccharp(self): x = c_char_p() self.assertEquals(x._objects, None) x.value = "abc" self.assertEquals(x._objects, "abc") x = c_char_p("spam") self.assertEquals(x._objects, "spam") class StructureTestCase(unittest.TestCase): def test_cint_struct(self): class X(Structure): _fields_ = [("a", c_int), ("b", c_int)] x = X() self.assertEquals(x._objects, None) x.a = 42 x.b = 99 self.assertEquals(x._objects, None) def test_ccharp_struct(self): class X(Structure): _fields_ = [("a", c_char_p), ("b", c_char_p)] x = X() self.assertEquals(x._objects, None) x.a = "spam" x.b = "foo" self.assertEquals(x._objects, {"0": "spam", "1": "foo"}) def test_struct_struct(self): class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] class RECT(Structure): _fields_ = [("ul", POINT), ("lr", POINT)] r = RECT() r.ul.x = 0 r.ul.y = 1 r.lr.x = 2 r.lr.y = 3 self.assertEquals(r._objects, None) r = RECT() pt = POINT(1, 2) r.ul = pt self.assertEquals(r._objects, {'0': {}}) r.ul.x = 22 r.ul.y = 44 self.assertEquals(r._objects, {'0': {}}) class ArrayTestCase(unittest.TestCase): def test_cint_array(self): INTARR = c_int * 3 ia = INTARR() self.assertEquals(ia._objects, None) ia[0] = 1 ia[1] = 2 ia[2] = 3 self.assertEquals(ia._objects, None) class X(Structure): _fields_ = [("x", c_int), ("a", INTARR)] x = X() x.x = 1000 x.a[0] = 42 x.a[1] = 96 self.assertEquals(x._objects, None) x.a = ia self.assertEquals(x._objects, {'1': {}}) class PointerTestCase(unittest.TestCase): def X_test_p_cint(self): x = pointer(c_int(42)) print x._objects class DeletePointerTestCase(unittest.TestCase): def X_test(self): class X(Structure): _fields_ = [("p", POINTER(c_char_p))] x = X() i = c_char_p("abc def") from sys import getrefcount as grc print "2?", grc(i) x.p = pointer(i) print "3?", grc(i) for i in range(320): c_int(99) x.p[0] print x.p[0] ## del x ## print "2?", grc(i) ## del i import gc gc.collect() for i in range(320): c_int(99) x.p[0] print x.p[0] print x.p.contents ## print x._objects x.p[0] = "spam spam" ## print x.p[0] print "+" * 42 print x._objects class PointerToStructure(unittest.TestCase): def test(self): class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] class RECT(Structure): _fields_ = [("a", POINTER(POINT)), ("b", POINTER(POINT))] r = RECT() p1 = POINT(1, 2) r.a = pointer(p1) r.b = pointer(p1) ## from pprint import pprint as pp ## pp(p1._objects) ## pp(r._objects) r.a[0].x = 42 r.a[0].y = 99 if __name__ == "__main__": unittest.main() --- NEW FILE: test_codegen.py --- import sys, os impor... [truncated message content] |
From: Thomas H. <th...@us...> - 2005-11-03 19:48:43
|
Update of /cvsroot/ctypes/ctypes/source In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4718 Modified Files: Tag: branch_1_0 _ctypes_test.c Log Message: Remove unused test functions. Index: _ctypes_test.c =================================================================== RCS file: /cvsroot/ctypes/ctypes/source/_ctypes_test.c,v retrieving revision 1.46.2.6 retrieving revision 1.46.2.7 diff -C2 -d -r1.46.2.6 -r1.46.2.7 *** _ctypes_test.c 20 Oct 2005 09:25:38 -0000 1.46.2.6 --- _ctypes_test.c 3 Nov 2005 19:48:32 -0000 1.46.2.7 *************** *** 62,96 **** } - /* attempt to isolate problems with glTexImage2D */ - EXPORT(unsigned int) _testfunc_glteximage2d( - unsigned int target, - int level, - int internalformat, - int width, - int height, - int border, - unsigned int format, - unsigned int type, - const void * pixels - ) { - /*printf( - "Hello world target=0x%x level=%i internalformat=%i width=%i height=%i border=%i format=0x%x type=0x%x\n", - target, level, internalformat, width, height, border, format, type - );*/ - return type; - } - EXPORT(unsigned int) _testfunc_glteximage2d2( - unsigned int target, - int level, - int internalformat, - int width, - int height, - int border, - unsigned int format, - unsigned int type - ) { - return type; - } - EXPORT(void *) get_strchr(void) { --- 62,65 ---- *************** *** 471,476 **** } RECT; - typedef int HWND; - #endif --- 440,443 ---- *************** *** 517,536 **** } ! EXPORT(HWND) my_GetDesktopWindow(void) ! { ! #ifdef MS_WIN32 ! return GetDesktopWindow(); ! #else ! return 42; ! #endif ! } ! ! EXPORT(int) my_GetWindowRect(HWND hwnd, RECT *prect) { ! #ifdef MS_WIN32 ! return GetWindowRect(hwnd, prect); ! #else ! return hwnd != 0; ! #endif } --- 484,496 ---- } ! EXPORT(int) GetRectangle(int flag, RECT *prect) { ! if (flag == 0) ! return 0; ! prect->left = (int)flag; ! prect->top = (int)flag + 1; ! prect->right = (int)flag + 2; ! prect->bottom = (int)flag + 3; ! return 1; } *************** *** 547,551 **** #ifdef MS_WIN32 ! /* Should port this to linux */ #include <stdlib.h> #include <search.h> --- 507,511 ---- #ifdef MS_WIN32 ! /* Should port this */ #include <stdlib.h> #include <search.h> *************** *** 590,593 **** --- 550,565 ---- return (void *)hThread; } + + EXPORT (HRESULT) KeepObject(IUnknown *punk) + { + static IUnknown *pobj; + if (punk) + punk->lpVtbl->AddRef(punk); + if (pobj) + pobj->lpVtbl->Release(pobj); + pobj = punk; + return S_OK; + } + #endif |
From: Thomas H. <th...@us...> - 2005-11-03 19:47:36
|
Update of /cvsroot/ctypes/ctypes/source In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4545 Modified Files: Tag: branch_1_0 cfield.c _ctypes.c Log Message: __repr__ is now implemented in C, for simple types like c_int, c_void_p, and so on. Index: cfield.c =================================================================== RCS file: /cvsroot/ctypes/ctypes/source/cfield.c,v retrieving revision 1.74.2.2 retrieving revision 1.74.2.3 diff -C2 -d -r1.74.2.2 -r1.74.2.3 *** cfield.c 28 Oct 2005 17:57:07 -0000 1.74.2.2 --- cfield.c 3 Nov 2005 19:47:27 -0000 1.74.2.3 *************** *** 943,949 **** { /* XXX What about invalid pointers ??? */ ! if (*(void **)ptr) return PyString_FromString(*(char **)ptr); ! else { Py_INCREF(Py_None); return Py_None; --- 943,957 ---- { /* XXX What about invalid pointers ??? */ ! if (*(void **)ptr) { ! #ifdef MS_WIN32 ! if (IsBadStringPtrA(*(char **)ptr, -1)) { ! PyErr_Format(PyExc_ValueError, ! "invalid string pointer %p", ! ptr); ! return NULL; ! } ! #endif return PyString_FromString(*(char **)ptr); ! } else { Py_INCREF(Py_None); return Py_None; Index: _ctypes.c =================================================================== RCS file: /cvsroot/ctypes/ctypes/source/_ctypes.c,v retrieving revision 1.226.2.33 retrieving revision 1.226.2.34 diff -C2 -d -r1.226.2.33 -r1.226.2.34 *** _ctypes.c 3 Nov 2005 07:31:28 -0000 1.226.2.33 --- _ctypes.c 3 Nov 2005 19:47:27 -0000 1.226.2.34 *************** *** 3710,3713 **** --- 3710,3752 ---- }; + /* "%s(%s)" % (self.__class__.__name__, self.value) */ + static PyObject * + Simple_repr(CDataObject *self) + { + PyObject *val, *name, *args, *result; + static PyObject *format; + + if (self->ob_type->tp_base != &Simple_Type) { + return PyString_FromFormat("<%s object at %p>", + self->ob_type->tp_name, self); + } + + if (format == NULL) { + format = PyString_FromString("%s(%r)"); + if (format == NULL) + return NULL; + } + + val = Simple_get_value(self); + if (val == NULL) + return NULL; + + name = PyString_FromString(self->ob_type->tp_name); + if (name == NULL) { + Py_DECREF(name); + return NULL; + } + + args = PyTuple_Pack(2, name, val); + Py_DECREF(name); + Py_DECREF(val); + if (args == NULL) + return NULL; + + result = PyString_Format(format, args); + Py_DECREF(args); + return result; + } + static PyTypeObject Simple_Type = { PyObject_HEAD_INIT(NULL) *************** *** 3721,3725 **** 0, /* tp_setattr */ 0, /* tp_compare */ ! 0, /* tp_repr */ &Simple_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ --- 3760,3764 ---- 0, /* tp_setattr */ 0, /* tp_compare */ ! (reprfunc)&Simple_repr, /* tp_repr */ &Simple_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ |
From: Thomas H. <th...@us...> - 2005-11-03 19:47:30
|
Update of /cvsroot/ctypes/ctypes/ctypes In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4518 Modified Files: Tag: branch_1_0 __init__.py Log Message: __repr__ is now implemented in C, for simple types like c_int, c_void_p, and so on. Index: __init__.py =================================================================== RCS file: /cvsroot/ctypes/ctypes/ctypes/__init__.py,v retrieving revision 1.61.2.11 retrieving revision 1.61.2.12 diff -C2 -d -r1.61.2.11 -r1.61.2.12 *** __init__.py 18 Oct 2005 19:15:44 -0000 1.61.2.11 --- __init__.py 3 Nov 2005 19:47:20 -0000 1.61.2.12 *************** *** 127,147 **** class c_short(_SimpleCData): _type_ = "h" - def __repr__(self): - return "%s(%d)" % (self.__class__.__name__, self.value) class c_ushort(_SimpleCData): _type_ = "H" - def __repr__(self): - return "%s(%d)" % (self.__class__.__name__, self.value) class c_long(_SimpleCData): _type_ = "l" - def __repr__(self): - return "%s(%d)" % (self.__class__.__name__, self.value) class c_ulong(_SimpleCData): _type_ = "L" - def __repr__(self): - return "%s(%d)" % (self.__class__.__name__, self.value) if _calcsize("i") == _calcsize("l"): --- 127,139 ---- *************** *** 152,172 **** class c_int(_SimpleCData): _type_ = "i" - def __repr__(self): - return "%s(%d)" % (self.__class__.__name__, self.value) class c_uint(_SimpleCData): _type_ = "I" - def __repr__(self): - return "%s(%d)" % (self.__class__.__name__, self.value) class c_float(_SimpleCData): _type_ = "f" - def __repr__(self): - return "%s(%f)" % (self.__class__.__name__, self.value) class c_double(_SimpleCData): _type_ = "d" - def __repr__(self): - return "%s(%f)" % (self.__class__.__name__, self.value) if _calcsize("l") == _calcsize("q"): --- 144,156 ---- *************** *** 177,187 **** class c_longlong(_SimpleCData): _type_ = "q" - def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, self.value) class c_ulonglong(_SimpleCData): _type_ = "Q" - def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, self.value) ## def from_param(cls, val): ## return ('d', float(val), val) --- 161,167 ---- *************** *** 190,195 **** class c_ubyte(_SimpleCData): _type_ = "B" - def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, self.value) # backward compatibility: ##c_uchar = c_ubyte --- 170,173 ---- *************** *** 197,226 **** class c_byte(_SimpleCData): _type_ = "b" - def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, self.value) class c_char(_SimpleCData): _type_ = "c" - def __repr__(self): - return "%s(%r)" % (self.__class__.__name__, self.value) class c_char_p(_SimpleCData): _type_ = "z" - if _os.name == "nt": - def __repr__(self): - if windll.kernel32.IsBadStringPtrA(self, -1): - ## return "%s(0x%x)" % (self.__class__.__name__, cast(self, c_uint).value) - return "%s(<invalid>)" % self.__class__.__name__ - else: - return "%s(%r)" % (self.__class__.__name__, self.value) - else: - def __repr__(self): - return "%s(%r)" % (self.__class__.__name__, self.value) class c_void_p(_SimpleCData): _type_ = "P" - def __repr__(self): - return "%s(%r)" % (self.__class__.__name__, self.value) - c_voidp = c_void_p # backwards compatibility (to a bug) --- 175,187 ---- *************** *** 259,277 **** class c_wchar_p(_SimpleCData): _type_ = "Z" - if _os.name == "nt": - def __repr__(self): - if windll.kernel32.IsBadStringPtrW(self, -1): - return "%s(<invalid>)" % self.__class__.__name__ - ## return "%s(0x%x)" % (self.__class__.__name__, cast(self, c_uint).value) - else: - return "%s(%r)" % (self.__class__.__name__, self.value) - else: - def __repr__(self): - return "%s(%r)" % (self.__class__.__name__, self.value) class c_wchar(_SimpleCData): _type_ = "u" - def __repr__(self): - return "%s(%r)" % (self.__class__.__name__, self.value) POINTER(c_wchar).from_param = c_wchar_p.from_param #_SimpleCData.c_wchar_p_from_param --- 220,226 ---- *************** *** 463,475 **** from decorators import stdcall ! # Later, these functions should examine the registry (or whatever) ! # to find out if they need ctypes.com.server or comtypes.server. def DllGetClassObject(rclsid, riid, ppv): ! # trick py2exe ! ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) ! return ctcom.DllGetClassObject(rclsid, riid, ppv) def DllCanUnloadNow(): ! # trick py2exe ! ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) ! return ctcom.DllCanUnloadNow() --- 412,459 ---- from decorators import stdcall ! if _os.name == "nt": # COM stuff def DllGetClassObject(rclsid, riid, ppv): ! # First ask ctypes.com.server than comtypes.server for the ! # class object. ! ! # trick py2exe by doing dynamic imports ! result = -2147221231 # CLASS_E_CLASSNOTAVAILABLE ! try: ! ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) ! except ImportError: ! pass ! else: ! result = ctcom.DllGetClassObject(rclsid, riid, ppv) ! ! if result == -2147221231: # CLASS_E_CLASSNOTAVAILABLE ! try: ! ccom = __import__("comtypes.server", globals(), locals(), ['*']) ! except ImportError: ! pass ! else: ! result = ccom.DllGetClassObject(rclsid, riid, ppv) ! ! return result def DllCanUnloadNow(): ! # First ask ctypes.com.server than comtypes.server if we can unload or not. ! # trick py2exe by doing dynamic imports ! result = 0 # S_OK ! try: ! ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) ! except ImportError: ! pass ! else: ! result = ctcom.DllCanUnloadNow() ! if result != 0: # != S_OK ! return result ! ! try: ! ccom = __import__("comtypes.server", globals(), locals(), ['*']) ! except ImportError: ! return result ! try: ! return ccom.DllCanUnloadNow() ! except AttributeError: ! pass ! return result |
From: Thomas H. <th...@us...> - 2005-11-03 19:22:20
|
Update of /cvsroot/ctypes/ctypes/ctypes/test In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv32241/test Log Message: Directory /cvsroot/ctypes/ctypes/ctypes/test added to the repository --> Using per-directory sticky tag `branch_1_0' |
From: Thomas H. <th...@us...> - 2005-11-03 07:35:11
|
Update of /cvsroot/ctypes/ctypes In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23302 Modified Files: Tag: branch_1_0 ChangeLog Log Message: *** empty log message *** Index: ChangeLog =================================================================== RCS file: /cvsroot/ctypes/ctypes/ChangeLog,v retrieving revision 1.86.2.26 retrieving revision 1.86.2.27 diff -C2 -d -r1.86.2.26 -r1.86.2.27 *** ChangeLog 28 Oct 2005 18:10:18 -0000 1.86.2.26 --- ChangeLog 3 Nov 2005 07:35:04 -0000 1.86.2.27 *************** *** 1,5 **** --- 1,22 ---- + 2005-11-03 Thomas Heller <th...@py...> + + * source\callbacks.c: For callback functions with result type None + ('void'), actually ignore the return value. Add some assert + statements for easier debugging. + + * source\_ctypes.c: Enable cycle GC on CFuncPtrType objects (does + not seem to have a visible effect). Fix quite some refcount leaks, + and a crash when outargs is NULL. Add some asserts for easier + debugging. + + * source\stgdict.c: Fixed a very nasty bug: The dict portion of + StgDict objects were never freed. Assigning a non-sequence to a + Structure _fields_ raises TypeError, not AttributeError. Fix + another refcount leak. + 2005-10-28 Thomas Heller <th...@py...> * setup.py: ctypes.macholib was missing in the packages list. + Remove the comtypes package from the tests. * source\cfield.c: Fix a refcount leak when unicode is converted |