SDL_PEEKEVENT = 1 SDL_GETEVENT = 2 SDL_eventaction = c_int SDL_PeepEvents = _bind( "SDL_PeepEvents", [POINTER(SDL_Event), c_int, SDL_eventaction, Uint32, Uint32], c_int) SDL_HasEvent = _bind("SDL_HasEvent", [Uint32], SDL_bool) SDL_HasEvents = _bind("SDL_HasEvents", [Uint32, Uint32], SDL_bool) SDL_FlushEvent = _bind("SDL_FlushEvent", [Uint32]) SDL_FlushEvents = _bind("SDL_FlushEvents", [Uint32, Uint32]) SDL_PollEvent = _bind("SDL_PollEvent", [POINTER(SDL_Event)], c_int) SDL_WaitEvent = _bind("SDL_WaitEvent", [POINTER(SDL_Event)], c_int) SDL_WaitEventTimeout = _bind("SDL_WaitEventTimeout", [POINTER(SDL_Event), c_int], c_int) SDL_PushEvent = _bind("SDL_PushEvent", [POINTER(SDL_Event)], c_int) SDL_EventFilter = CFUNCTYPE(c_int, c_void_p, POINTER(SDL_Event)) SDL_SetEventFilter = _bind("SDL_SetEventFilter", [SDL_EventFilter, c_void_p]) SDL_GetEventFilter = _bind( "SDL_GetEventFilter", [POINTER(SDL_EventFilter), POINTER(c_void_p)], SDL_bool) SDL_AddEventWatch = _bind("SDL_AddEventWatch", [SDL_EventFilter, c_void_p]) SDL_DelEventWatch = _bind("SDL_DelEventWatch", [SDL_EventFilter, c_void_p]) SDL_FilterEvents = _bind("SDL_FilterEvents", [SDL_EventFilter, c_void_p]) SDL_QUERY = -1 SDL_IGNORE = 0 SDL_DISABLE = 0 SDL_ENABLE = 1 SDL_EventState = _bind("SDL_EventState", [Uint32, c_int], Uint8) SDL_GetEventState = lambda t: SDL_EventState(t, SDL_QUERY) SDL_RegisterEvents = _bind("SDL_RegisterEvents", [c_int], Uint32)
def prototype(lgeos, geos_version): """Protype functions in geos_c.h for different version of GEOS Use the GEOS version, not the C API version. """ if not geos_version >= (3, 3, 0): raise UnsupportedGEOSVersionError( "Shapely requires GEOS version 3.3.0 or newer.") # Initialization, cleanup, version. lgeos.initGEOS.restype = None lgeos.initGEOS.argtypes = [ EXCEPTION_HANDLER_FUNCTYPE, EXCEPTION_HANDLER_FUNCTYPE] lgeos.finishGEOS.restype = None lgeos.finishGEOS.argtypes = [] lgeos.GEOSversion.restype = c_char_p lgeos.GEOSversion.argtypes = [] # These functions are DEPRECATED. Please use the new Reader and # writer APIS! lgeos.GEOSGeomFromWKT.restype = c_void_p lgeos.GEOSGeomFromWKT.argtypes = [c_char_p] lgeos.GEOSGeomToWKT.restype = allocated_c_char_p lgeos.GEOSGeomToWKT.argtypes = [c_void_p] lgeos.GEOS_setWKBOutputDims.restype = c_int lgeos.GEOS_setWKBOutputDims.argtypes = [c_int] lgeos.GEOSGeomFromWKB_buf.restype = c_void_p lgeos.GEOSGeomFromWKB_buf.argtypes = [c_void_p, c_size_t] lgeos.GEOSGeomToWKB_buf.restype = allocated_c_char_p lgeos.GEOSGeomToWKB_buf.argtypes = [c_void_p, c_size_t_p] # Coordinate sequence lgeos.GEOSCoordSeq_create.restype = c_void_p lgeos.GEOSCoordSeq_create.argtypes = [c_uint, c_uint] lgeos.GEOSCoordSeq_clone.restype = c_void_p lgeos.GEOSCoordSeq_clone.argtypes = [c_void_p] lgeos.GEOSGeom_clone.restype = c_void_p lgeos.GEOSGeom_clone.argtypes = [c_void_p] lgeos.GEOSCoordSeq_destroy.restype = None lgeos.GEOSCoordSeq_destroy.argtypes = [c_void_p] lgeos.GEOSCoordSeq_setX.restype = c_int lgeos.GEOSCoordSeq_setX.argtypes = [c_void_p, c_uint, c_double] lgeos.GEOSCoordSeq_setY.restype = c_int lgeos.GEOSCoordSeq_setY.argtypes = [c_void_p, c_uint, c_double] lgeos.GEOSCoordSeq_setZ.restype = c_int lgeos.GEOSCoordSeq_setZ.argtypes = [c_void_p, c_uint, c_double] lgeos.GEOSCoordSeq_setOrdinate.restype = c_int lgeos.GEOSCoordSeq_setOrdinate.argtypes = [ c_void_p, c_uint, c_uint, c_double] lgeos.GEOSCoordSeq_getX.restype = c_int lgeos.GEOSCoordSeq_getX.argtypes = [c_void_p, c_uint, c_void_p] lgeos.GEOSCoordSeq_getY.restype = c_int lgeos.GEOSCoordSeq_getY.argtypes = [c_void_p, c_uint, c_void_p] lgeos.GEOSCoordSeq_getZ.restype = c_int lgeos.GEOSCoordSeq_getZ.argtypes = [c_void_p, c_uint, c_void_p] lgeos.GEOSCoordSeq_getSize.restype = c_int lgeos.GEOSCoordSeq_getSize.argtypes = [c_void_p, c_void_p] lgeos.GEOSCoordSeq_getDimensions.restype = c_int lgeos.GEOSCoordSeq_getDimensions.argtypes = [c_void_p, c_void_p] # Linear refeferencing if geos_version >= (3, 2, 0): lgeos.GEOSProject.restype = c_double lgeos.GEOSProject.argtypes = [c_void_p, c_void_p] lgeos.GEOSInterpolate.restype = c_void_p lgeos.GEOSInterpolate.argtypes = [c_void_p, c_double] lgeos.GEOSProjectNormalized.restype = c_double lgeos.GEOSProjectNormalized.argtypes = [c_void_p, c_void_p] lgeos.GEOSInterpolateNormalized.restype = c_void_p lgeos.GEOSInterpolateNormalized.argtypes = [c_void_p, c_double] # Buffer related lgeos.GEOSBuffer.restype = c_void_p lgeos.GEOSBuffer.argtypes = [c_void_p, c_double, c_int] if geos_version >= (3, 2, 0): lgeos.GEOSBufferWithStyle.restype = c_void_p lgeos.GEOSBufferWithStyle.argtypes = [ c_void_p, c_double, c_int, c_int, c_int, c_double] if geos_version >= (3, 3, 0): lgeos.GEOSOffsetCurve.restype = c_void_p lgeos.GEOSOffsetCurve.argtypes = [ c_void_p, c_double, c_int, c_int, c_double] else: # deprecated in GEOS 3.3.0 in favour of GEOSOffsetCurve lgeos.GEOSSingleSidedBuffer.restype = c_void_p lgeos.GEOSSingleSidedBuffer.argtypes = [ c_void_p, c_double, c_int, c_int, c_double, c_int] # Geometry constructors lgeos.GEOSGeom_createPoint.restype = c_void_p lgeos.GEOSGeom_createPoint.argtypes = [c_void_p] lgeos.GEOSGeom_createLinearRing.restype = c_void_p lgeos.GEOSGeom_createLinearRing.argtypes = [c_void_p] lgeos.GEOSGeom_createLineString.restype = c_void_p lgeos.GEOSGeom_createLineString.argtypes = [c_void_p] lgeos.GEOSGeom_createPolygon.restype = c_void_p lgeos.GEOSGeom_createPolygon.argtypes = [c_void_p, c_void_p, c_uint] lgeos.GEOSGeom_createCollection.restype = c_void_p lgeos.GEOSGeom_createCollection.argtypes = [c_int, c_void_p, c_uint] if geos_version >= (3, 3, 0): lgeos.GEOSGeom_createEmptyCollection.restype = c_void_p lgeos.GEOSGeom_createEmptyCollection.argtypes = [c_int] lgeos.GEOSGeom_clone.restype = c_void_p lgeos.GEOSGeom_clone.argtypes = [c_void_p] # Memory management lgeos.GEOSGeom_destroy.restype = None lgeos.GEOSGeom_destroy.argtypes = [c_void_p] # Topology operations # Return NULL on exception lgeos.GEOSEnvelope.restype = c_void_p lgeos.GEOSEnvelope.argtypes = [c_void_p] lgeos.GEOSIntersection.restype = c_void_p lgeos.GEOSIntersection.argtypes = [c_void_p, c_void_p] lgeos.GEOSConvexHull.restype = c_void_p lgeos.GEOSConvexHull.argtypes = [c_void_p] lgeos.GEOSDifference.restype = c_void_p lgeos.GEOSDifference.argtypes = [c_void_p, c_void_p] lgeos.GEOSSymDifference.restype = c_void_p lgeos.GEOSSymDifference.argtypes = [c_void_p, c_void_p] lgeos.GEOSBoundary.restype = c_void_p lgeos.GEOSBoundary.argtypes = [c_void_p] lgeos.GEOSUnion.restype = c_void_p lgeos.GEOSUnion.argtypes = [c_void_p, c_void_p] if geos_version >= (3, 3, 0): lgeos.GEOSUnaryUnion.restype = c_void_p lgeos.GEOSUnaryUnion.argtypes = [c_void_p] if geos_version >= (3, 1, 0): # deprecated in 3.3.0: use GEOSUnaryUnion instead lgeos.GEOSUnionCascaded.restype = c_void_p lgeos.GEOSUnionCascaded.argtypes = [c_void_p] lgeos.GEOSPointOnSurface.restype = c_void_p lgeos.GEOSPointOnSurface.argtypes = [c_void_p] lgeos.GEOSGetCentroid.restype = c_void_p lgeos.GEOSGetCentroid.argtypes = [c_void_p] lgeos.GEOSPolygonize.restype = c_void_p lgeos.GEOSPolygonize.argtypes = [c_void_p, c_uint] if geos_version >= (3, 3, 0): lgeos.GEOSPolygonize_full.restype = c_void_p lgeos.GEOSPolygonize_full.argtypes = [ c_void_p, c_void_p, c_void_p, c_void_p] if geos_version >= (3, 4, 0): lgeos.GEOSDelaunayTriangulation.restype = c_void_p lgeos.GEOSDelaunayTriangulation.argtypes = [c_void_p, c_double, c_int] lgeos.GEOSLineMerge.restype = c_void_p lgeos.GEOSLineMerge.argtypes = [c_void_p] lgeos.GEOSSimplify.restype = c_void_p lgeos.GEOSSimplify.argtypes = [c_void_p, c_double] lgeos.GEOSTopologyPreserveSimplify.restype = c_void_p lgeos.GEOSTopologyPreserveSimplify.argtypes = [c_void_p, c_double] # Binary predicates # Return 2 on exception, 1 on true, 0 on false lgeos.GEOSDisjoint.restype = c_byte lgeos.GEOSDisjoint.argtypes = [c_void_p, c_void_p] lgeos.GEOSTouches.restype = c_byte lgeos.GEOSTouches.argtypes = [c_void_p, c_void_p] lgeos.GEOSIntersects.restype = c_byte lgeos.GEOSIntersects.argtypes = [c_void_p, c_void_p] lgeos.GEOSCrosses.restype = c_byte lgeos.GEOSCrosses.argtypes = [c_void_p, c_void_p] lgeos.GEOSWithin.restype = c_byte lgeos.GEOSWithin.argtypes = [c_void_p, c_void_p] lgeos.GEOSContains.restype = c_byte lgeos.GEOSContains.argtypes = [c_void_p, c_void_p] lgeos.GEOSOverlaps.restype = c_byte lgeos.GEOSOverlaps.argtypes = [c_void_p, c_void_p] lgeos.GEOSCovers.restype = c_byte lgeos.GEOSCovers.argtypes = [c_void_p, c_void_p] lgeos.GEOSEquals.restype = c_byte lgeos.GEOSEquals.argtypes = [c_void_p, c_void_p] lgeos.GEOSEqualsExact.restype = c_byte lgeos.GEOSEqualsExact.argtypes = [c_void_p, c_void_p, c_double] # Unary predicate # Return 2 on exception, 1 on true, 0 on false lgeos.GEOSisEmpty.restype = c_byte lgeos.GEOSisEmpty.argtypes = [c_void_p] lgeos.GEOSisValid.restype = c_byte lgeos.GEOSisValid.argtypes = [c_void_p] if geos_version >= (3, 1, 0): lgeos.GEOSisValidReason.restype = allocated_c_char_p lgeos.GEOSisValidReason.argtypes = [c_void_p] lgeos.GEOSisSimple.restype = c_byte lgeos.GEOSisSimple.argtypes = [c_void_p] lgeos.GEOSisRing.restype = c_byte lgeos.GEOSisRing.argtypes = [c_void_p] if geos_version >= (3, 3, 0): lgeos.GEOSisClosed.restype = c_byte lgeos.GEOSisClosed.argtypes = [c_void_p] lgeos.GEOSHasZ.restype = c_byte lgeos.GEOSHasZ.argtypes = [c_void_p] # Dimensionally Extended 9 Intersection Model related lgeos.GEOSRelate.restype = allocated_c_char_p lgeos.GEOSRelate.argtypes = [c_void_p, c_void_p] lgeos.GEOSRelatePattern.restype = c_byte lgeos.GEOSRelatePattern.argtypes = [c_void_p, c_void_p, c_char_p] if geos_version >= (3, 3, 0): lgeos.GEOSRelatePatternMatch.restype = c_byte lgeos.GEOSRelatePatternMatch.argtypes = [c_char_p, c_char_p] # Prepared Geometry Binary predicates # Return 2 on exception, 1 on true, 0 on false if geos_version >= (3, 1, 0): lgeos.GEOSPrepare.restype = c_void_p lgeos.GEOSPrepare.argtypes = [c_void_p] lgeos.GEOSPreparedGeom_destroy.restype = None lgeos.GEOSPreparedGeom_destroy.argtypes = [c_void_p] lgeos.GEOSPreparedDisjoint.restype = c_byte lgeos.GEOSPreparedDisjoint.argtypes = [c_void_p, c_void_p] lgeos.GEOSPreparedTouches.restype = c_byte lgeos.GEOSPreparedTouches.argtypes = [c_void_p, c_void_p] lgeos.GEOSPreparedIntersects.restype = c_byte lgeos.GEOSPreparedIntersects.argtypes = [c_void_p, c_void_p] lgeos.GEOSPreparedCrosses.restype = c_byte lgeos.GEOSPreparedCrosses.argtypes = [c_void_p, c_void_p] lgeos.GEOSPreparedWithin.restype = c_byte lgeos.GEOSPreparedWithin.argtypes = [c_void_p, c_void_p] lgeos.GEOSPreparedContains.restype = c_byte lgeos.GEOSPreparedContains.argtypes = [c_void_p, c_void_p] lgeos.GEOSPreparedContainsProperly.restype = c_byte lgeos.GEOSPreparedContainsProperly.argtypes = [c_void_p, c_void_p] lgeos.GEOSPreparedOverlaps.restype = c_byte lgeos.GEOSPreparedOverlaps.argtypes = [c_void_p, c_void_p] lgeos.GEOSPreparedCovers.restype = c_byte lgeos.GEOSPreparedCovers.argtypes = [c_void_p, c_void_p] # Geometry info lgeos.GEOSGeomType.restype = c_char_p lgeos.GEOSGeomType.argtypes = [c_void_p] lgeos.GEOSGeomTypeId.restype = c_int lgeos.GEOSGeomTypeId.argtypes = [c_void_p] lgeos.GEOSGetSRID.restype = c_int lgeos.GEOSGetSRID.argtypes = [c_void_p] lgeos.GEOSSetSRID.restype = None lgeos.GEOSSetSRID.argtypes = [c_void_p, c_int] lgeos.GEOSGetNumGeometries.restype = c_int lgeos.GEOSGetNumGeometries.argtypes = [c_void_p] lgeos.GEOSGetGeometryN.restype = c_void_p lgeos.GEOSGetGeometryN.argtypes = [c_void_p, c_int] lgeos.GEOSGetNumInteriorRings.restype = c_int lgeos.GEOSGetNumInteriorRings.argtypes = [c_void_p] lgeos.GEOSGetInteriorRingN.restype = c_void_p lgeos.GEOSGetInteriorRingN.argtypes = [c_void_p, c_int] lgeos.GEOSGetExteriorRing.restype = c_void_p lgeos.GEOSGetExteriorRing.argtypes = [c_void_p] lgeos.GEOSGetNumCoordinates.restype = c_int lgeos.GEOSGetNumCoordinates.argtypes = [c_void_p] lgeos.GEOSGeom_getCoordSeq.restype = c_void_p lgeos.GEOSGeom_getCoordSeq.argtypes = [c_void_p] lgeos.GEOSGeom_getDimensions.restype = c_int lgeos.GEOSGeom_getDimensions.argtypes = [c_void_p] # Misc functions lgeos.GEOSArea.restype = c_double lgeos.GEOSArea.argtypes = [c_void_p, c_void_p] lgeos.GEOSLength.restype = c_int lgeos.GEOSLength.argtypes = [c_void_p, c_void_p] lgeos.GEOSDistance.restype = c_int lgeos.GEOSDistance.argtypes = [c_void_p, c_void_p, c_void_p] if geos_version >= (3, 2, 0): lgeos.GEOSHausdorffDistance.restype = c_int lgeos.GEOSHausdorffDistance.argtypes = [c_void_p, c_void_p, c_void_p] # Reader and Writer APIs lgeos.GEOSWKTReader_create.restype = c_void_p lgeos.GEOSWKTReader_create.argtypes = [] lgeos.GEOSWKTReader_destroy.restype = None lgeos.GEOSWKTReader_destroy.argtypes = [c_void_p] lgeos.GEOSWKTReader_read.restype = c_void_p lgeos.GEOSWKTReader_read.argtypes = [c_void_p, c_char_p] lgeos.GEOSWKTWriter_create.restype = c_void_p lgeos.GEOSWKTWriter_create.argtypes = [] lgeos.GEOSWKTWriter_destroy.restype = None lgeos.GEOSWKTWriter_destroy.argtypes = [c_void_p] lgeos.GEOSWKTWriter_write.restype = allocated_c_char_p lgeos.GEOSWKTWriter_write.argtypes = [c_void_p, c_void_p] if geos_version >= (3, 3, 0): lgeos.GEOSWKTWriter_setTrim.restype = None lgeos.GEOSWKTWriter_setTrim.argtypes = [c_void_p, c_int] lgeos.GEOSWKTWriter_setRoundingPrecision.restype = None lgeos.GEOSWKTWriter_setRoundingPrecision.argtypes = [c_void_p, c_int] lgeos.GEOSWKTWriter_setOutputDimension.restype = None lgeos.GEOSWKTWriter_setOutputDimension.argtypes = [c_void_p, c_int] lgeos.GEOSWKTWriter_getOutputDimension.restype = c_int lgeos.GEOSWKTWriter_getOutputDimension.argtypes = [c_void_p] lgeos.GEOSWKTWriter_setOld3D.restype = None lgeos.GEOSWKTWriter_setOld3D.argtypes = [c_void_p, c_int] lgeos.GEOSWKBReader_create.restype = c_void_p lgeos.GEOSWKBReader_create.argtypes = [] lgeos.GEOSWKBReader_destroy.restype = None lgeos.GEOSWKBReader_destroy.argtypes = [c_void_p] lgeos.GEOSWKBReader_read.restype = c_void_p lgeos.GEOSWKBReader_read.argtypes = [c_void_p, c_char_p, c_size_t] lgeos.GEOSWKBReader_readHEX.restype = c_void_p lgeos.GEOSWKBReader_readHEX.argtypes = [c_void_p, c_char_p, c_size_t] lgeos.GEOSWKBWriter_create.restype = c_void_p lgeos.GEOSWKBWriter_create.argtypes = [] lgeos.GEOSWKBWriter_destroy.restype = None lgeos.GEOSWKBWriter_destroy.argtypes = [c_void_p] lgeos.GEOSWKBWriter_write.restype = allocated_c_char_p lgeos.GEOSWKBWriter_write.argtypes = [c_void_p, c_void_p, c_size_t_p] lgeos.GEOSWKBWriter_writeHEX.restype = allocated_c_char_p lgeos.GEOSWKBWriter_writeHEX.argtypes = [c_void_p, c_void_p, c_size_t_p] lgeos.GEOSWKBWriter_getOutputDimension.restype = c_int lgeos.GEOSWKBWriter_getOutputDimension.argtypes = [c_void_p] lgeos.GEOSWKBWriter_setOutputDimension.restype = None lgeos.GEOSWKBWriter_setOutputDimension.argtypes = [c_void_p, c_int] lgeos.GEOSWKBWriter_getByteOrder.restype = c_int lgeos.GEOSWKBWriter_getByteOrder.argtypes = [c_void_p] lgeos.GEOSWKBWriter_setByteOrder.restype = None lgeos.GEOSWKBWriter_setByteOrder.argtypes = [c_void_p, c_int] lgeos.GEOSWKBWriter_getIncludeSRID.restype = c_int lgeos.GEOSWKBWriter_getIncludeSRID.argtypes = [c_void_p] lgeos.GEOSWKBWriter_setIncludeSRID.restype = None lgeos.GEOSWKBWriter_setIncludeSRID.argtypes = [c_void_p, c_int] if geos_version >= (3, 1, 1): lgeos.GEOSFree.restype = None lgeos.GEOSFree.argtypes = [c_void_p] if geos_version >= (3, 3, 0): lgeos.GEOSSnap.restype = c_void_p lgeos.GEOSSnap.argtypes = [c_void_p, c_void_p, c_double] lgeos.GEOSSharedPaths.restype = c_void_p lgeos.GEOSSharedPaths.argtypes = [c_void_p, c_void_p] if geos_version >= (3, 4, 0): lgeos.GEOSNearestPoints.restype = c_void_p lgeos.GEOSNearestPoints.argtypes = [c_void_p, c_void_p] if geos_version >= (3, 4, 2): lgeos.GEOSQueryCallback = CFUNCTYPE(None, c_void_p, c_void_p) lgeos.GEOSSTRtree_query.argtypes = [ c_void_p, c_void_p, lgeos.GEOSQueryCallback, py_object] lgeos.GEOSSTRtree_query.restype = None lgeos.GEOSSTRtree_create.argtypes = [c_int] lgeos.GEOSSTRtree_create.restype = c_void_p lgeos.GEOSSTRtree_insert.argtypes = [c_void_p, c_void_p, py_object] lgeos.GEOSSTRtree_insert.restype = None lgeos.GEOSSTRtree_remove.argtypes = [c_void_p, c_void_p, py_object] lgeos.GEOSSTRtree_remove.restype = None lgeos.GEOSSTRtree_destroy.argtypes = [c_void_p] lgeos.GEOSSTRtree_destroy.restype = None
# No GEOS library could be found. if lib_path is None: raise ImportError('Could not find the GEOS library (tried "%s"). ' 'Try setting GEOS_LIBRARY_PATH in your settings.' % '", "'.join(lib_names)) # Getting the GEOS C library. The C interface (CDLL) is used for # both *NIX and Windows. # See the GEOS C API source code for more details on the library function calls: # http://geos.refractions.net/ro/doxygen_docs/html/geos__c_8h-source.html lgeos = CDLL(lib_path) # The notice and error handler C function callback definitions. # Supposed to mimic the GEOS message handler (C below): # typedef void (*GEOSMessageHandler)(const char *fmt, ...); NOTICEFUNC = CFUNCTYPE(None, c_char_p, c_char_p) def notice_h(fmt, lst, output_h=sys.stdout): try: warn_msg = fmt % lst except: warn_msg = fmt output_h.write('GEOS_NOTICE: %s\n' % warn_msg) notice_h = NOTICEFUNC(notice_h) ERRORFUNC = CFUNCTYPE(None, c_char_p, c_char_p)
if platform == "win32": from ctypes import WINFUNCTYPE as CFUNCTYPE _tessellator = gluNewTess() # Winding rule determines the regions that should be filled and those that should remain unshaded. # Winding direction is determined by the normal. gluTessProperty(_tessellator, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_NONZERO) gluTessNormal(_tessellator, 0, 0, 1) # As tessellation proceeds, callback routines are called in a manner # similar to OpenGL commands glBegin(), glEdgeFlag*(), glVertex*(), and glEnd(). # The callback functions must be C functions so we need to cast our Python callbacks to C. _tessellate_callback_type = { GLU_TESS_VERTEX: CFUNCTYPE(None, POINTER(GLvoid)), GLU_TESS_BEGIN: CFUNCTYPE(None, GLenum), GLU_TESS_END: CFUNCTYPE(None), GLU_TESS_ERROR: CFUNCTYPE(None, GLenum), GLU_TESS_COMBINE: CFUNCTYPE(None, POINTER(GLdouble), POINTER(POINTER(GLvoid)), POINTER(GLfloat), POINTER(POINTER(GLvoid))) } # One path with a 100 points is somewhere around 15KB. TESSELLATION_CACHE = 100
@dataclass class AttributeWriteResult: path: AttributePath status: int # typedef void (*PythonInteractionModelDelegate_OnCommandResponseStatusCodeReceivedFunct)(uint64_t commandSenderPtr, # void * commandStatusBuf); # typedef void (*PythonInteractionModelDelegate_OnCommandResponseProtocolErrorFunct)(uint64_t commandSenderPtr, uint8_t commandIndex); # typedef void (*PythonInteractionModelDelegate_OnCommandResponseFunct)(uint64_t commandSenderPtr, uint32_t error); # typedef void (*PythonInteractionModelDelegate_OnReportDataFunct)(chip::NodeId nodeId, uint64_t readClientAppIdentifier, # void * attributePathBuf, size_t attributePathBufLen, # uint8_t * readTlvData, size_t readTlvDataLen, uint16_t statusCode); _OnCommandResponseStatusCodeReceivedFunct = CFUNCTYPE(None, c_uint64, c_void_p, c_uint32) _OnCommandResponseProtocolErrorFunct = CFUNCTYPE(None, c_uint64, c_uint8) _OnCommandResponseFunct = CFUNCTYPE(None, c_uint64, c_uint32) _OnReportDataFunct = CFUNCTYPE(None, c_uint64, c_uint64, c_ssize_t, c_void_p, c_uint32, c_void_p, c_uint32, c_uint16) _OnWriteResponseStatusFunct = CFUNCTYPE(None, c_void_p, c_uint32) _commandStatusDict = dict() _commandIndexStatusDict = dict() _commandStatusLock = threading.RLock() _commandStatusCV = threading.Condition(_commandStatusLock) _attributeDict = dict() _attributeDictLock = threading.RLock() _writeStatusDict = dict()
("green", POINTER(c_ushort)), ("blue", POINTER(c_ushort)), ("size", c_int), ] class GLFWwindow(Structure): pass class GLFWmonitor(Structure): pass # --- Callbacks --------------------------------------------------------------- errorfun = CFUNCTYPE(None, c_int, c_char_p) windowposfun = CFUNCTYPE(None, POINTER(GLFWwindow), c_int, c_int) windowsizefun = CFUNCTYPE(None, POINTER(GLFWwindow), c_int, c_int) windowclosefun = CFUNCTYPE(None, POINTER(GLFWwindow)) windowrefreshfun = CFUNCTYPE(None, POINTER(GLFWwindow)) windowfocusfun = CFUNCTYPE(None, POINTER(GLFWwindow), c_int) windowiconifyfun = CFUNCTYPE(None, POINTER(GLFWwindow), c_int) framebuffersizefun = CFUNCTYPE(None, POINTER(GLFWwindow), c_int, c_int) mousebuttonfun = CFUNCTYPE(None, POINTER(GLFWwindow), c_int, c_int, c_int) cursorposfun = CFUNCTYPE(None, POINTER(GLFWwindow), c_double, c_double) cursorenterfun = CFUNCTYPE(None, POINTER(GLFWwindow), c_int) scrollfun = CFUNCTYPE(None, POINTER(GLFWwindow), c_double, c_double) keyfun = CFUNCTYPE(None, POINTER(GLFWwindow), c_int, c_int, c_int, c_int) charfun = CFUNCTYPE(None, POINTER(GLFWwindow), c_uint) monitorfun = CFUNCTYPE(None, POINTER(GLFWmonitor), c_int) dropfun = CFUNCTYPE(None, POINTER(GLFWmonitor), c_int, POINTER(c_char_p))
dtrace_aggdata, dtrace_recdesc from threading import Thread import threading import time cdll.LoadLibrary("libdtrace.so") LIBRARY = CDLL("libdtrace.so") # ============================================================================= # chewing and output walkers # ============================================================================= CHEW_FUNC = CFUNCTYPE(c_int, POINTER(dtrace_probedata), POINTER(c_void_p)) CHEWREC_FUNC = CFUNCTYPE(c_int, POINTER(dtrace_probedata), POINTER(dtrace_recdesc), POINTER(c_void_p)) BUFFERED_FUNC = CFUNCTYPE(c_int, POINTER(dtrace_bufdata), POINTER(c_void_p)) WALK_FUNC = CFUNCTYPE(c_int, POINTER(dtrace_aggdata), POINTER(c_void_p)) def simple_chew_func(data, arg): """
('time', DWORD), ('dwExtraInfo', ULONG_PTR)) class HARDWAREINPUT(ctypes.Structure): _fields_ = (('uMsg', DWORD), ('wParamL', WORD), ('wParamH', WORD)) class _INPUTunion(ctypes.Union): _fields_ = (('mi', MOUSEINPUT), ('ki', KEYBDINPUT), ('hi', HARDWAREINPUT)) class INPUT(ctypes.Structure): _fields_ = (('type', DWORD), ('union', _INPUTunion)) LowLevelKeyboardProc = CFUNCTYPE(c_int, WPARAM, LPARAM, POINTER(KBDLLHOOKSTRUCT)) SetWindowsHookEx = user32.SetWindowsHookExW #SetWindowsHookEx.argtypes = [c_int, LowLevelKeyboardProc, c_int, c_int] SetWindowsHookEx.restype = HHOOK CallNextHookEx = user32.CallNextHookEx #CallNextHookEx.argtypes = [c_int , c_int, c_int, POINTER(KBDLLHOOKSTRUCT)] CallNextHookEx.restype = c_int UnhookWindowsHookEx = user32.UnhookWindowsHookEx UnhookWindowsHookEx.argtypes = [HHOOK] UnhookWindowsHookEx.restype = BOOL GetMessage = user32.GetMessageW GetMessage.argtypes = [LPMSG, c_int, c_int, c_int]
# -*- coding: utf-8 -*- from .common import loadOde from ctypes import CFUNCTYPE from ctypes import c_void_p from ctypes import c_int32 dAllocFunction = CFUNCTYPE(c_void_p, c_int32) dReallocFunction = CFUNCTYPE(c_void_p, c_void_p, c_int32, c_int32) dFreeFunction = CFUNCTYPE(None, c_void_p, c_int32) dSetAllocHandler = loadOde('dSetAllocHandler', None, dAllocFunction) dSetReallocHandler = loadOde('dSetReallocHandler', None, dReallocFunction) dSetFreeHandler = loadOde('dSetFreeHandler', None, dFreeFunction) dGetAllocHandler = loadOde('dGetAllocHandler', dAllocFunction) dGetReallocHandler = loadOde('dGetReallocHandler', dReallocFunction) dGetFreeHandler = loadOde('dGetFreeHandler', dFreeFunction) dAlloc = loadOde('dAlloc', c_void_p, c_int32) dRealloc = loadOde('dRealloc', c_void_p, c_void_p, c_int32, c_int32) dFree = loadOde('dFree', None, c_void_p, c_int32)
ver = gdal_version().decode() m = version_regex.match(ver) if not m: raise GDALException('Could not parse GDAL version string "%s"' % ver) return {key: m.group(key) for key in ('major', 'minor', 'subminor')} _verinfo = gdal_version_info() GDAL_MAJOR_VERSION = int(_verinfo['major']) GDAL_MINOR_VERSION = int(_verinfo['minor']) GDAL_SUBMINOR_VERSION = _verinfo['subminor'] and int(_verinfo['subminor']) GDAL_VERSION = (GDAL_MAJOR_VERSION, GDAL_MINOR_VERSION, GDAL_SUBMINOR_VERSION) del _verinfo # Set library error handling so as errors are logged CPLErrorHandler = CFUNCTYPE(None, c_int, c_int, c_char_p) def err_handler(error_class, error_number, message): logger.error('GDAL_ERROR %d: %s', error_number, message) err_handler = CPLErrorHandler(err_handler) def function(name, args, restype): func = std_call(name) func.argtypes = args func.restype = restype return func
stream.start_stream() self.reset() data = stream.read(CHUNK) # Read a new chunk from the stream if LISTENING: stream.write(data, CHUNK) except KeyboardInterrupt: stream.stop_stream() stream.close() p.terminate() # self.loop.quit() raise KeyboardInterrupt ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p) def py_error_handler(filename, line, function, err, fmt): pass c_error_handler = ERROR_HANDLER_FUNC(py_error_handler) @contextmanager def noalsaerr(): asound = cdll.LoadLibrary('libasound.so') asound.snd_lib_error_set_handler(c_error_handler) yield asound.snd_lib_error_set_handler(None)
ONE_i32 = ll.Constant(i32, 1) MEMORY_MASK_i32 = ll.Constant(i32, MEMORY_SIZE - 1) def getc(): return sys.stdin.read(1) def putc(c): sys.stdout.write(chr(c & 0x7f)) sys.stdout.flush() # These need to be GLOBAL, otherwise the GC will clean it up, making it # uncallable from the JIT. PUTC_WRAPPER = CFUNCTYPE(None, c_int8)(putc) GETC_WRAPPER = CFUNCTYPE(c_int8)(getc) def compile_bf(prog): """ Compiles the given BF program text into a llvm.ModuleRef object. The module will contain 3 globals: - the main function, void bfmain() - the memory, int8_t memory[] - the memory index, int32_t index """ module = ll.Module() func = ll.Function(module, ll.FunctionType(ll.VoidType(), []), 'bfmain') builder = ll.IRBuilder()
def _launch_threads(): with _backend_init_process_lock: with _backend_init_thread_lock: global _is_initialized if _is_initialized: return from ctypes import CFUNCTYPE, c_int def select_known_backend(backend): """ Loads a specific threading layer backend based on string """ lib = None if backend.startswith("tbb"): try: from . import tbbpool as lib except ImportError: pass elif backend.startswith("omp"): # TODO: Check that if MKL is present that it is a version that # understands GNU OMP might be present try: from . import omppool as lib except ImportError: pass elif backend.startswith("workqueue"): from . import workqueue as lib else: msg = "Unknown value specified for threading layer: %s" raise ValueError(msg % backend) return lib def select_from_backends(backends): """ Selects from presented backends and returns the first working """ lib = None for backend in backends: lib = select_known_backend(backend) if lib is not None: break else: backend = '' return lib, backend t = str(config.THREADING_LAYER).lower() namedbackends = ['tbb', 'omp', 'workqueue'] lib = None _IS_OSX = platform.system() == "Darwin" _IS_LINUX = platform.system() == "Linux" err_helpers = dict() err_helpers['TBB'] = ("Intel TBB is required, try:\n" "$ conda/pip install tbb") err_helpers['OSX_OMP'] = ("Intel OpenMP is required, try:\n" "$ conda/pip install intel-openmp") requirements = [] def raise_with_hint(required): errmsg = "No threading layer could be loaded.\n%s" hintmsg = "HINT:\n%s" if len(required) == 0: hint = '' if len(required) == 1: hint = hintmsg % err_helpers[required[0]] if len(required) > 1: options = '\nOR\n'.join([err_helpers[x] for x in required]) hint = hintmsg % ("One of:\n%s" % options) raise ValueError(errmsg % hint) if t in namedbackends: # Try and load the specific named backend lib = select_known_backend(t) if not lib: # something is missing preventing a valid backend from # loading, set requirements for hinting if t == 'tbb': requirements.append('TBB') elif t == 'omp' and _IS_OSX: requirements.append('OSX_OMP') libname = t elif t in ['threadsafe', 'forksafe', 'safe']: # User wants a specific behaviour... available = ['tbb'] requirements.append('TBB') if t == "safe": # "safe" is TBB, which is fork and threadsafe everywhere pass elif t == "threadsafe": if _IS_OSX: requirements.append('OSX_OMP') # omp is threadsafe everywhere available.append('omp') elif t == "forksafe": # everywhere apart from linux (GNU OpenMP) has a guaranteed # forksafe OpenMP, as OpenMP has better performance, prefer # this to workqueue if not _IS_LINUX: available.append('omp') if _IS_OSX: requirements.append('OSX_OMP') # workqueue is forksafe everywhere available.append('workqueue') else: # unreachable msg = "No threading layer available for purpose %s" raise ValueError(msg % t) # select amongst available lib, libname = select_from_backends(available) elif t == 'default': # If default is supplied, try them in order, tbb, omp, # workqueue lib, libname = select_from_backends(namedbackends) if not lib: # set requirements for hinting requirements.append('TBB') if _IS_OSX: requirements.append('OSX_OMP') else: msg = "The threading layer requested '%s' is unknown to Numba." raise ValueError(msg % t) # No lib found, raise and hint if not lib: raise_with_hint(requirements) ll.add_symbol('numba_parallel_for', lib.parallel_for) ll.add_symbol('do_scheduling_signed', lib.do_scheduling_signed) ll.add_symbol('do_scheduling_unsigned', lib.do_scheduling_unsigned) launch_threads = CFUNCTYPE(None, c_int)(lib.launch_threads) launch_threads(NUM_THREADS) # set library name so it can be queried global _threading_layer _threading_layer = libname _is_initialized = True
def test_ll_pointer_cast(self): """ Usecase test: custom reinterpret cast to turn int values to pointers """ from ctypes import CFUNCTYPE, POINTER, c_float, c_int # Use intrinsic to make a reinterpret_cast operation def unsafe_caster(result_type): assert isinstance(result_type, types.CPointer) @intrinsic def unsafe_cast(typingctx, src): self.assertIsInstance(typingctx, typing.Context) if isinstance(src, types.Integer): sig = result_type(types.uintp) # defines the custom code generation def codegen(context, builder, signature, args): [src] = args rtype = signature.return_type llrtype = context.get_value_type(rtype) return builder.inttoptr(src, llrtype) return sig, codegen return unsafe_cast # make a nopython function to use our cast op. # this is not usable from cpython due to the returning of a pointer. def unsafe_get_ctypes_pointer(src): raise NotImplementedError("not callable from python") @overload(unsafe_get_ctypes_pointer, strict=False) def array_impl_unsafe_get_ctypes_pointer(arrtype): if isinstance(arrtype, types.Array): unsafe_cast = unsafe_caster(types.CPointer(arrtype.dtype)) def array_impl(arr): return unsafe_cast(src=arr.ctypes.data) return array_impl # the ctype wrapped function for use in nopython mode def my_c_fun_raw(ptr, n): for i in range(n): print(ptr[i]) prototype = CFUNCTYPE(None, POINTER(c_float), c_int) my_c_fun = prototype(my_c_fun_raw) # Call our pointer-cast in a @jit compiled function and use # the pointer in a ctypes function @jit(nopython=True) def foo(arr): ptr = unsafe_get_ctypes_pointer(arr) my_c_fun(ptr, arr.size) # Test arr = np.arange(10, dtype=np.float32) with captured_stdout() as buf: foo(arr) got = buf.getvalue().splitlines() buf.close() expect = list(map(str, arr)) self.assertEqual(expect, got)
P_hackrf_device = POINTER(hackrf_device) class hackrf_transfer(Structure): _fields_ = [ ("hackrf_device", P_hackrf_device), ("buffer", POINTER(c_byte)), ("buffer_length", c_int), ("valid_length", c_int), ("rx_ctx", c_void_p), ("tx_ctx", c_void_p) ] P_hackrf_transfer = POINTER(hackrf_transfer) _callback = CFUNCTYPE(c_int, P_hackrf_transfer) hackrf_device._fields_ = [ ("usb_device", POINTER(c_void_p)), ("transfers", POINTER(P_hackrf_transfer)), ("callback", _callback), ("transfer_thread_started", c_int), ("transfer_thread", c_ulong), ("transfer_count", c_uint32), ("buffer_size", c_uint32), ("streaming", c_int), ("rx_ctx", c_void_p), ("tx_ctx", c_void_p) ] def enum(*sequential, **named):
def setup_callbacks_posix(self): # ptr_R_Suicide if self.show_message: self.ptr_show_message = CFUNCTYPE(None, c_char_p)(self.show_message) ptr = c_void_p.in_dll(self.libR, 'ptr_R_ShowMessage') ptr.value = cast(self.ptr_show_message, c_void_p).value if self.read_console: # make sure it is not gc'ed self.ptr_read_console = \ CFUNCTYPE(c_int, c_char_p, POINTER(c_char), c_int, c_int)(self.read_console) ptr = c_void_p.in_dll(self.libR, 'ptr_R_ReadConsole') ptr.value = cast(self.ptr_read_console, c_void_p).value if self.write_console_ex: c_void_p.in_dll(self.libR, 'ptr_R_WriteConsole').value = None # make sure it is not gc'ed self.ptr_write_console_ex = \ CFUNCTYPE(None, c_char_p, c_int, c_int)(self.write_console_ex) ptr = c_void_p.in_dll(self.libR, 'ptr_R_WriteConsoleEx') ptr.value = cast(self.ptr_write_console_ex, c_void_p).value # ptr_R_ResetConsole # ptr_R_FlushConsole # ptr_R_ClearerrConsole if self.r_busy: self.ptr_r_busy = CFUNCTYPE(None, c_int)(self.r_busy) ptr = c_void_p.in_dll(self.libR, 'ptr_R_Busy') ptr.value = cast(self.ptr_r_busy, c_void_p).value if self.clean_up: ptr = c_void_p.in_dll(self.libR, 'ptr_R_CleanUp') R_CleanUp = CFUNCTYPE(None, c_int, c_int, c_int)(ptr.value) def _handler(save_type, status, runlast): self.clean_up(save_type, status, runlast) R_CleanUp(save_type, status, runlast) self.ptr_r_clean_up = CFUNCTYPE(None, c_int, c_int, c_int)(_handler) ptr.value = cast(self.ptr_r_clean_up, c_void_p).value # ptr_R_ShowFiles # ptr_R_ChooseFile # ptr_R_EditFile # ptr_R_loadhistory # ptr_R_savehistory # ptr_R_addhistory # ptr_R_EditFiles # ptr_do_selectlist # ptr_do_dataentry # ptr_do_dataviewer if self.process_event: self.ptr_process_event = CFUNCTYPE(None)(self.process_event) ptr = c_void_p.in_dll(self.libR, 'ptr_R_ProcessEvents') ptr.value = cast(self.ptr_process_event, c_void_p).value if self.polled_events: self.ptr_polled_events = CFUNCTYPE(None)(self.polled_events) ptr = c_void_p.in_dll(self.libR, 'R_PolledEvents') ptr.value = cast(self.ptr_polled_events, c_void_p).value
def __init__(self, libpath): if libpath is None: libpath = get_library_path() lib = load_library(libpath) def create_func(fn, restype, argtypes): f = lib.__getattr__(fn) f.restype = restype f.argtypes = argtypes return f self.CorsairSetLedsColorsBufferByDeviceIndex = create_func( 'CorsairSetLedsColorsBufferByDeviceIndex', c_bool, [c_int32, c_int32, POINTER(CorsairLedColor)]) self.CorsairSetLedsColorsFlushBuffer = create_func( 'CorsairSetLedsColorsFlushBuffer', c_bool, None) self.CallbackFunc = CFUNCTYPE(c_void_p, c_bool, CorsairError) self.CorsairSetLedsColorsFlushBufferAsync = create_func( 'CorsairSetLedsColorsFlushBufferAsync', c_bool, [self.CallbackFunc, c_void_p]) self.CorsairGetLedsColors = create_func( 'CorsairGetLedsColors', c_bool, [c_int32, POINTER(CorsairLedColor)]) self.CorsairGetLedsColorsByDeviceIndex = create_func( 'CorsairGetLedsColorsByDeviceIndex', c_bool, [c_int32, c_int32, POINTER(CorsairLedColor)]) self.CorsairGetDeviceCount = create_func('CorsairGetDeviceCount', c_int32, None) self.CorsairGetDeviceInfo = create_func('CorsairGetDeviceInfo', POINTER(CorsairDeviceInfo), [c_int32]) self.CorsairGetLedPositions = create_func('CorsairGetLedPositions', POINTER(CorsairLedPositions), None) self.CorsairGetLedPositionsByDeviceIndex = create_func( 'CorsairGetLedPositionsByDeviceIndex', POINTER(CorsairLedPositions), [c_int32]) self.CorsairGetLedIdForKeyName = create_func( 'CorsairGetLedIdForKeyName', CorsairLedId, [c_char]) self.CorsairRequestControl = create_func('CorsairRequestControl', c_bool, [CorsairAccessMode]) self.CorsairPerformProtocolHandshake = create_func( 'CorsairPerformProtocolHandshake', CorsairProtocolDetails, None) self.CorsairGetLastError = create_func('CorsairGetLastError', CorsairError, None) self.CorsairReleaseControl = create_func('CorsairReleaseControl', c_bool, [CorsairAccessMode]) self.CorsairSetLayerPriority = create_func('CorsairSetLayerPriority', c_bool, [c_int32]) c_bool_p = POINTER(c_bool) self.CorsairGetBoolPropertyValue = create_func( 'CorsairGetBoolPropertyValue', c_bool, [c_int32, CorsairDevicePropertyId, c_bool_p]) c_int32_p = POINTER(c_int32) self.CorsairGetInt32PropertyValue = create_func( 'CorsairGetInt32PropertyValue', c_bool, [c_int32, CorsairDevicePropertyId, c_int32_p]) self.EventHandler = CFUNCTYPE(None, c_void_p, POINTER(CorsairEvent)) self.CorsairSubscribeForEvents = create_func( 'CorsairSubscribeForEvents', c_bool, [self.EventHandler, c_void_p]) self.CorsairUnsubscribeFromEvents = create_func( 'CorsairUnsubscribeFromEvents', c_bool, None)
((c_int, "ret"), (SSL_CIPHER, "cipher"), (POINTER(c_int), "alg_bits", 1, None)), True, None), ("EC_get_builtin_curves", libcrypto, ((c_int, "ret"), (POINTER(EC_builtin_curve), "r"), (c_int, "nitems"))), ("EC_KEY_new_by_curve_name", libcrypto, ((EC_KEY, "ret"), (c_int, "nid"))), ("EC_KEY_free", libcrypto, ((None, "ret"), (EC_KEY, "key"))), ("EC_curve_nist2nid", libcrypto, ((c_int, "ret"), (POINTER(c_char), "name")), True, None), ("EC_curve_nid2nist", libcrypto, ((c_char_p, "ret"), (c_int, "nid")), True, None), )) # # Wrappers - functions generally equivalent to OpenSSL library macros # _rvoid_int_int_charp_int = CFUNCTYPE(None, c_int, c_int, c_char_p, c_int) def CRYPTO_set_locking_callback(locking_function): def py_locking_function(mode, n, file, line): try: locking_function(mode, n, file, line) except: _logger.exception("Thread locking failed") global _locking_cb # for keep-alive _locking_cb = _rvoid_int_int_charp_int(py_locking_function) _CRYPTO_set_locking_callback(_locking_cb) def SSL_CTX_set_session_cache_mode(ctx, mode):
class PamMessage(Structure): """wrapper class for pam_message structure""" _fields_ = [ ("msg_style", c_int), ("msg", c_char_p) ] def __repr__(self): return "<PamMessage %i '%s'>" % (self.msg_style, self.msg) class PamResponse(Structure): """wrapper class for pam_response structure""" _fields_ = [ ("resp", c_char_p), ("resp_retcode", c_int) ] def __repr__(self): return "<PamResponse %i '%s'>" % (self.resp_retcode, self.resp) conv_func = CFUNCTYPE(c_int, c_int, POINTER(POINTER(PamMessage)), POINTER(POINTER(PamResponse)), c_void_p) class PamConv(Structure): """wrapper class for pam_conv structure""" _fields_ = [ ("conv", conv_func), ("appdata_ptr", c_void_p) ] # Various constants PAM_PROMPT_ECHO_OFF = 1 PAM_PROMPT_ECHO_ON = 2 PAM_ERROR_MSG = 3 PAM_TEXT_INFO = 4 PAM_REINITIALIZE_CRED = 8 libc = CDLL(find_library("c")) libpam = CDLL(find_library("pam"))
Have a look at examples on GitHub: https://github.com/rnd-team-dev/plotoptix. """ import os, platform, sys from ctypes import cdll, CFUNCTYPE, POINTER, byref, cast, c_float, c_uint, c_int, c_long, c_bool, c_char_p, c_wchar_p, c_void_p BIN_PATH = "bin" PLATFORM = platform.system() if PLATFORM == "Linux": import clr from System import IntPtr, Int64 PARAM_NONE_CALLBACK = CFUNCTYPE(None) PARAM_INT_CALLBACK = CFUNCTYPE(None, c_int) denoiser_loaded = False def load_denoiser(): global denoiser_loaded if denoiser_loaded: return True if PLATFORM == "Windows": cudnn_lib = os.path.join(os.path.dirname(__file__), BIN_PATH, "cudnn64_7.dll") denoiser_lib = os.path.join(os.path.dirname(__file__), BIN_PATH, "optix_denoiser.6.0.0.dll")
from __future__ import absolute_import import os from ctypes import CDLL, RTLD_GLOBAL, CFUNCTYPE, c_int, byref, c_void_p, c_char_p from mxnet.base import check_call, NDArrayHandle from mxnet.ndarray import NDArray from mxnet.ndarray import zeros from ..common import get_ext_suffix from ..common.bytetask import ByteTask # Load c_lib.so dll_path = os.path.join(os.path.dirname(__file__), 'c_lib' + get_ext_suffix()) BYTESCHEDULER_LIB = CDLL(dll_path, RTLD_GLOBAL) callback_t = CFUNCTYPE(None, c_void_p) barrier_tensors = {} def get_barrier_tensor(key): global barrier_tensors if key not in barrier_tensors: barrier_tensors[key] = zeros(1) return barrier_tensors[key] class KVStoreTask(ByteTask): def _additional_init(self): if self.op == "push_pull": if self.parent is not None: assert len(self._tensor) == self._num_workers
libssl = CDLL(libssl_path, use_errno=True) P_SSL_METHOD = POINTER(c_void_p) P_SSL_CTX = POINTER(c_void_p) P_SSL_SESSION = POINTER(c_void_p) P_SSL = POINTER(c_void_p) P_BIO_METHOD = POINTER(c_void_p) P_BIO = POINTER(c_void_p) X509 = c_void_p P_X509 = POINTER(X509) P_X509_STORE = POINTER(c_void_p) P_X509_STORE_CTX = POINTER(c_void_p) try: stack_cmp_func = CFUNCTYPE(c_int, c_void_p, c_void_p) setattr(libssl, 'stack_cmp_func', stack_cmp_func) class _STACK(Structure): _fields_ = [ ('num', c_int), ('data', POINTER(P_X509)), ('sorted', c_int), ('num_alloc', c_int), ('comp', stack_cmp_func), ] libssl.SSL_library_init.argtypes = [] libssl.SSL_library_init.restype = c_int libssl.OPENSSL_add_all_algorithms_noconf.argtypes = []
('SA_AMF_ADMIN_LOCK_INSTANTIATION', 3), ('SA_AMF_ADMIN_UNLOCK_INSTANTIATION', 4), ('SA_AMF_ADMIN_SHUTDOWN', 5), ('SA_AMF_ADMIN_RESTART', 6), ('SA_AMF_ADMIN_SI_SWAP', 7), ('SA_AMF_ADMIN_SG_ADJUST', 8), ('SA_AMF_ADMIN_REPAIRED', 9), ('SA_AMF_ADMIN_EAM_START', 10), ('SA_AMF_ADMIN_EAM_STOP', 11), )) #*************************************************/ #******** AMF API function declarations **********/ #*************************************************/ SaAmfHealthcheckCallbackT = CFUNCTYPE(None, SaInvocationT, POINTER(SaNameT), POINTER(SaAmfHealthcheckKeyT)) SaAmfComponentTerminateCallbackT = CFUNCTYPE(None, SaInvocationT, POINTER(SaNameT)) SaAmfCSISetCallbackT = CFUNCTYPE(None, SaInvocationT, POINTER(SaNameT), SaAmfHAStateT, SaAmfCSIDescriptorT) SaAmfCSIRemoveCallbackT = CFUNCTYPE(None, SaInvocationT, POINTER(SaNameT), POINTER(SaNameT), SaAmfCSIFlagsT) #if defined(SA_AMF_B01) || defined(SA_AMF_B02) || defined(SA_AMF_B03) SaAmfProtectionGroupTrackCallbackT = CFUNCTYPE(None, POINTER(SaNameT), POINTER(SaAmfProtectionGroupNotificationBufferT), SaUint32T, SaAisErrorT)
("guessed_category", c_uint16), ("guessed_header_category", c_uint16), ("l4_proto", c_uint8), ("protocol_id_already_guessed", c_uint8, 1), ("host_already_guessed", c_uint8, 1), ("init_finished", c_uint8, 1), ("setup_packet_direction", c_uint8, 1), ("packet_direction", c_uint8, 1), ("check_extra_packets", c_uint8, 1), ("next_tcp_seq_nr", c_uint32 * 2), ("max_extra_packets_to_check", c_uint8), ("num_extra_packets_checked", c_uint8), ("num_processed_pkts", c_uint8), ("extra_packets_func", CFUNCTYPE(c_int, POINTER(NDPIDetectionModuleStruct), POINTER(NDPIFlowStruct))), ("l4", L4), ("server_id", POINTER(NDPIIdStruct)), ("host_server_name", c_ubyte * 256), ("http", Http), ("protos", Protos), ("excluded_protocol_bitmask", NDPIProtocolBitMask), ("category", c_int), ('redis_s2d_first_char', c_uint8), ('redis_d2s_first_char', c_uint8), ('packet_counter', c_uint16), ('packet_direction_counter', c_uint16 * 2), ('byte_counter', c_uint16 * 2), ('bittorrent_stage', c_uint8), ('directconnect_stage', c_uint8, 2), ('sip_yahoo_voice', c_uint8, 1), ('http_detected', c_uint8, 1),
'''Prototyping of the GEOS C API See header file: geos-x.y.z/capi/geos_c.h ''' from ctypes import CFUNCTYPE, POINTER, c_void_p, c_char_p, \ c_size_t, c_byte, c_uint, c_int, c_double, py_object from .errors import UnsupportedGEOSVersionError EXCEPTION_HANDLER_FUNCTYPE = CFUNCTYPE(None, c_char_p, c_void_p) # Derived pointer types c_size_t_p = POINTER(c_size_t) class allocated_c_char_p(c_char_p): '''char pointer return type''' pass def prototype(lgeos, geos_version): """Protype functions in geos_c.h for different version of GEOS Use the GEOS version, not the C API version. """ if not geos_version >= (3, 3, 0): raise UnsupportedGEOSVersionError( "Shapely requires GEOS version 3.3.0 or newer.")
class NDPISubprotocolConfStruct(Structure): _fields_ = [("func", CFUNCTYPE(c_void_p, POINTER(NDPIDetectionModuleStruct), c_char_p, c_char_p, c_int))]
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. """ import functools from ctypes import c_int, c_double, c_char_p, POINTER, CFUNCTYPE, byref from .support_types import SpiceCell UDFUNS = CFUNCTYPE(None, c_double, POINTER(c_double)) UDFUNB = CFUNCTYPE(None, UDFUNS, c_double, POINTER(c_int)) UDSTEP = CFUNCTYPE(None, c_double, POINTER(c_double)) UDREFN = CFUNCTYPE(None, c_double, c_double, c_int, c_int, POINTER(c_double)) UDREPI = CFUNCTYPE(None, POINTER(SpiceCell), c_char_p, c_char_p) UDREPU = CFUNCTYPE(None, c_double, c_double, c_double) UDREPF = CFUNCTYPE(None) UDBAIL = CFUNCTYPE(c_int) def SpiceUDFUNS(f): """ Decorator for wrapping python functions in spice udfuns callback type :param f: function that has one argument of type float, and returns a float :type f: builtins.function :return: wrapped udfunc function
Args: name(string): 表名 Returns: (Table) 打开的Table指针 Raises: TeraSdkException: 打开table时出错 """ err = c_char_p() table_ptr = lib.tera_table_open(self.client, name, byref(err)) if table_ptr is None: raise TeraSdkException("open table failed:" + err.value) return Table(table_ptr) MUTATION_CALLBACK = CFUNCTYPE(None, c_void_p) class RowMutation(object): """ 对某一行的变更 在Table.ApplyMutation()调用之前, RowMutation的所有操作(如Put/DeleteColumn)都不会立即生效 """ def __init__(self, mutation): self.mutation = mutation def PutKV(self, value, ttl): """ 写入(修改)值为<value> Args:
raise NotImplementedError def function_callback(real_cb, context, nargs, c_params): params = _convert_params(context, nargs, c_params) try: val = real_cb(*params) except Exception, e: msg = "user-defined function raised exception" sqlite.sqlite3_result_error(context, msg, len(msg)) else: _convert_result(context, val) return 0 FUNC = CFUNCTYPE(c_int, c_void_p, c_int, POINTER(c_void_p)) STEP = CFUNCTYPE(c_int, c_void_p, c_int, POINTER(c_void_p)) FINAL = CFUNCTYPE(c_int, c_void_p) sqlite.sqlite3_create_function.argtypes = [ c_void_p, c_char_p, c_int, c_int, c_void_p, FUNC, STEP, FINAL ] sqlite.sqlite3_create_function.restype = c_int converters = {} adapters = {} class PrepareProtocol(object): pass
class PamResponse(Structure): ''' Wrapper class for pam_response structure ''' _fields_ = [ ('resp', c_char_p), ('resp_retcode', c_int), ] def __repr__(self): return '<PamResponse {0} \'{1}\'>'.format(self.resp_retcode, self.resp) CONV_FUNC = CFUNCTYPE(c_int, c_int, POINTER(POINTER(PamMessage)), POINTER(POINTER(PamResponse)), c_void_p) class PamConv(Structure): ''' Wrapper class for pam_conv structure ''' _fields_ = [('conv', CONV_FUNC), ('appdata_ptr', c_void_p)] try: PAM_START = LIBPAM.pam_start PAM_START.restype = c_int PAM_START.argtypes = [ c_char_p, c_char_p, POINTER(PamConv),