def _parse_typedefs(self):
"""
Determines the ctypes data types of the Task and Cal handles
based on the version of the NI-DAQmx driver installed.
"""
from nidaqmx.system.system import System
system = System.local()
# If DAQmx 8.8 and lower, TaskHandle is a typedef for uInt32 since
# DAQmx didn't support 64-bit applications then.
version = system.driver_version
if version.major_version <= 8 and version.minor_version <= 8:
self._task_handle = ctypes.c_uint
else:
self._task_handle = ctypes.c_void_p
self._cal_handle = ctypes.c_uint
python类c_void_p()的实例源码
def to_rain(cls, val):
if val is None:
return cls.new(typi.null, 0, 0, cls.null)
elif val is False:
return cls.new(typi.bool, 0, 0, cls.null)
elif val is True:
return cls.new(typi.bool, 0, 1, cls.null)
elif isinstance(val, int):
return cls.new(typi.int, 0, val, cls.null)
elif isinstance(val, float):
raw = struct.pack('d', val)
intrep = struct.unpack('Q', raw)[0]
return cls.new(typi.float, 0, intrep, cls.null)
elif isinstance(val, str):
str_p = ct.create_string_buffer(val.encode('utf-8'))
cls._saves_.append(str_p)
return cls.new(typi.str, len(val), ct.cast(str_p, ct.c_void_p).value, cls.null)
raise Exception("Can't convert value {!r} to Rain".format(val))
def rawaddressof(self, BTypePtr, cdata, offset=None):
if isinstance(cdata, CTypesBaseStructOrUnion):
ptr = ctypes.pointer(type(cdata)._to_ctypes(cdata))
elif isinstance(cdata, CTypesGenericPtr):
if offset is None or not issubclass(type(cdata)._BItem,
CTypesBaseStructOrUnion):
raise TypeError("unexpected cdata type")
ptr = type(cdata)._to_ctypes(cdata)
elif isinstance(cdata, CTypesGenericArray):
ptr = type(cdata)._to_ctypes(cdata)
else:
raise TypeError("expected a <cdata 'struct-or-union'>")
if offset:
ptr = ctypes.cast(
ctypes.c_void_p(
ctypes.cast(ptr, ctypes.c_void_p).value + offset),
type(ptr))
return BTypePtr._from_ctypes(ptr)
def hook_keyboard(callback):
handle = None
def low_level_callback(code, rparam, lparam):
try:
key_code = 0xFFFFFFFF & lparam[0] # key code
callback(key_code, rparam & 0xFFFFFFFF)
finally:
return CallNextHookEx(handle, code, rparam, lparam)
# The really big problem is the callback_pointer.
# Once it goes out of scope, it is destroyed
callback_pointer = CFUNCTYPE(c_int, c_int, wintypes.HINSTANCE, POINTER(c_void_p))(low_level_callback)
__CALLBACK_POINTERS.append(callback_pointer)
handle = SetWindowsHookExA(WH_KEYBOARD_LL, callback_pointer, GetModuleHandleA(None), 0)
atexit.register(UnhookWindowsHookEx, handle)
return handle
def hook_keyboard():
def handler(key_code, event_code):
print("{0} {1}".format(hex(key_code), hex(event_code)))
handle = None
def low_level_callback(code, rparam, lparam):
try:
key_code = 0xFFFFFFFF & lparam[0] # key code
handler(key_code, rparam & 0xFFFFFFFF)
finally:
return CallNextHookEx(handle, code, rparam, lparam)
callback_pointer = CFUNCTYPE(c_int, c_int, wintypes.HINSTANCE, POINTER(c_void_p))(low_level_callback)
handle = SetWindowsHookExA(WH_KEYBOARD_LL, callback_pointer, GetModuleHandleA(None), 0)
atexit.register(UnhookWindowsHookEx, handle)
def on_exit():
pass
funcs.shell__pump_messages(on_exit)
def libvlc_media_new_location(p_instance, psz_mrl):
'''Create a media with a certain given media resource location,
for instance a valid URL.
@note: To refer to a local file with this function,
the file://... URI syntax B{must} be used (see IETF RFC3986).
We recommend using L{libvlc_media_new_path}() instead when dealing with
local files.
See L{libvlc_media_release}.
@param p_instance: the instance.
@param psz_mrl: the media location.
@return: the newly created media or None on error.
'''
f = _Cfunctions.get('libvlc_media_new_location', None) or \
_Cfunction('libvlc_media_new_location', ((1,), (1,),), class_result(Media),
ctypes.c_void_p, Instance, ctypes.c_char_p)
return f(p_instance, psz_mrl)
def libvlc_media_new_fd(p_instance, fd):
'''Create a media for an already open file descriptor.
The file descriptor shall be open for reading (or reading and writing).
Regular file descriptors, pipe read descriptors and character device
descriptors (including TTYs) are supported on all platforms.
Block device descriptors are supported where available.
Directory descriptors are supported on systems that provide fdopendir().
Sockets are supported on all platforms where they are file descriptors,
i.e. all except Windows.
@note: This library will B{not} automatically close the file descriptor
under any circumstance. Nevertheless, a file descriptor can usually only be
rendered once in a media player. To render it a second time, the file
descriptor should probably be rewound to the beginning with lseek().
See L{libvlc_media_release}.
@param p_instance: the instance.
@param fd: open file descriptor.
@return: the newly created media or None on error.
@version: LibVLC 1.1.5 and later.
'''
f = _Cfunctions.get('libvlc_media_new_fd', None) or \
_Cfunction('libvlc_media_new_fd', ((1,), (1,),), class_result(Media),
ctypes.c_void_p, Instance, ctypes.c_int)
return f(p_instance, fd)
def libvlc_media_get_meta(p_md, e_meta):
'''Read the meta of the media.
If the media has not yet been parsed this will return None.
This methods automatically calls L{libvlc_media_parse_async}(), so after calling
it you may receive a libvlc_MediaMetaChanged event. If you prefer a synchronous
version ensure that you call L{libvlc_media_parse}() before get_meta().
See L{libvlc_media_parse}
See L{libvlc_media_parse_async}
See libvlc_MediaMetaChanged.
@param p_md: the media descriptor.
@param e_meta: the meta to read.
@return: the media's meta.
'''
f = _Cfunctions.get('libvlc_media_get_meta', None) or \
_Cfunction('libvlc_media_get_meta', ((1,), (1,),), string_result,
ctypes.c_void_p, Media, Meta)
return f(p_md, e_meta)
def libvlc_media_discoverer_new(p_inst, psz_name):
'''Create a media discoverer object by name.
After this object is created, you should attach to events in order to be
notified of the discoverer state.
You should also attach to media_list events in order to be notified of new
items discovered.
You need to call L{libvlc_media_discoverer_start}() in order to start the
discovery.
See L{libvlc_media_discoverer_media_list}
See L{libvlc_media_discoverer_event_manager}
See L{libvlc_media_discoverer_start}.
@param p_inst: libvlc instance.
@param psz_name: service name; use L{libvlc_media_discoverer_list_get}() to get a list of the discoverer names available in this libVLC instance.
@return: media discover object or None in case of error.
@version: LibVLC 3.0.0 or later.
'''
f = _Cfunctions.get('libvlc_media_discoverer_new', None) or \
_Cfunction('libvlc_media_discoverer_new', ((1,), (1,),), class_result(MediaDiscoverer),
ctypes.c_void_p, Instance, ctypes.c_char_p)
return f(p_inst, psz_name)
def libvlc_video_set_callbacks(mp, lock, unlock, display, opaque):
'''Set callbacks and private data to render decoded video to a custom area
in memory.
Use L{libvlc_video_set_format}() or L{libvlc_video_set_format_callbacks}()
to configure the decoded format.
@param mp: the media player.
@param lock: callback to lock video memory (must not be None).
@param unlock: callback to unlock video memory (or None if not needed).
@param display: callback to display video (or None if not needed).
@param opaque: private pointer for the three callbacks (as first parameter).
@version: LibVLC 1.1.1 or later.
'''
f = _Cfunctions.get('libvlc_video_set_callbacks', None) or \
_Cfunction('libvlc_video_set_callbacks', ((1,), (1,), (1,), (1,), (1,),), None,
None, MediaPlayer, VideoLockCb, VideoUnlockCb, VideoDisplayCb, ctypes.c_void_p)
return f(mp, lock, unlock, display, opaque)
def libvlc_audio_set_callbacks(mp, play, pause, resume, flush, drain, opaque):
'''Sets callbacks and private data for decoded audio.
Use L{libvlc_audio_set_format}() or L{libvlc_audio_set_format_callbacks}()
to configure the decoded audio format.
@note: The audio callbacks override any other audio output mechanism.
If the callbacks are set, LibVLC will B{not} output audio in any way.
@param mp: the media player.
@param play: callback to play audio samples (must not be None).
@param pause: callback to pause playback (or None to ignore).
@param resume: callback to resume playback (or None to ignore).
@param flush: callback to flush audio buffers (or None to ignore).
@param drain: callback to drain audio buffers (or None to ignore).
@param opaque: private pointer for the audio callbacks (as first parameter).
@version: LibVLC 2.0.0 or later.
'''
f = _Cfunctions.get('libvlc_audio_set_callbacks', None) or \
_Cfunction('libvlc_audio_set_callbacks', ((1,), (1,), (1,), (1,), (1,), (1,), (1,),), None,
None, MediaPlayer, AudioPlayCb, AudioPauseCb, AudioResumeCb, AudioFlushCb, AudioDrainCb, ctypes.c_void_p)
return f(mp, play, pause, resume, flush, drain, opaque)
def libvlc_media_player_set_equalizer(p_mi, p_equalizer):
'''Apply new equalizer settings to a media player.
The equalizer is first created by invoking L{libvlc_audio_equalizer_new}() or
L{libvlc_audio_equalizer_new_from_preset}().
It is possible to apply new equalizer settings to a media player whether the media
player is currently playing media or not.
Invoking this method will immediately apply the new equalizer settings to the audio
output of the currently playing media if there is any.
If there is no currently playing media, the new equalizer settings will be applied
later if and when new media is played.
Equalizer settings will automatically be applied to subsequently played media.
To disable the equalizer for a media player invoke this method passing None for the
p_equalizer parameter.
The media player does not keep a reference to the supplied equalizer so it is safe
for an application to release the equalizer reference any time after this method
returns.
@param p_mi: opaque media player handle.
@param p_equalizer: opaque equalizer handle, or None to disable the equalizer for this media player.
@return: zero on success, -1 on error.
@version: LibVLC 2.2.0 or later.
'''
f = _Cfunctions.get('libvlc_media_player_set_equalizer', None) or \
_Cfunction('libvlc_media_player_set_equalizer', ((1,), (1,),), None,
ctypes.c_int, MediaPlayer, ctypes.c_void_p)
return f(p_mi, p_equalizer)
def libvlc_vlm_show_media(p_instance, psz_name):
'''Return information about the named media as a JSON
string representation.
This function is mainly intended for debugging use,
if you want programmatic access to the state of
a vlm_media_instance_t, please use the corresponding
libvlc_vlm_get_media_instance_xxx -functions.
Currently there are no such functions available for
vlm_media_t though.
@param p_instance: the instance.
@param psz_name: the name of the media, if the name is an empty string, all media is described.
@return: string with information about named media, or None on error.
'''
f = _Cfunctions.get('libvlc_vlm_show_media', None) or \
_Cfunction('libvlc_vlm_show_media', ((1,), (1,),), string_result,
ctypes.c_void_p, Instance, ctypes.c_char_p)
return f(p_instance, psz_name)
def try_enc():
import os
inFile = open('x.wav', 'rb')
inFile.seek(0, os.SEEK_END)
wavFileSize = inFile.tell()
inFile.seek(44) # skip wav header
outFile = open('x.mp3', 'wb')
lame = LameEncoder(44100,1,128)
while(1):
inBytes = inFile.read(512)
if inBytes == '':
break
#inBuf = ctypes.create_string_buffer(inBytes, 512)
sample_count = len(inBytes) /2
output_buff_len = int(1.25 * sample_count + 7200)
output_buff = (ctypes.c_char*output_buff_len)()
lame.dll.lame_encode_buffer.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_char), ctypes.c_int];
output_size = lame.dll.lame_encode_buffer(lame.lame, inBytes, 0, len(inBytes)/2, output_buff, output_buff_len);
outFile.write(output_buff[0:output_size])
outFile.close()
def get_window_prop(dpy, window, prop_name, max_size=2):
"""
Returns (nitems, property) of specified window or (-1, None) if anything fails.
Returned 'property' is POINTER(c_void_p) and has to be freed using X.free().
"""
prop_atom = intern_atom(dpy, prop_name, False)
type_return, format_return = Atom(), Atom()
nitems, bytes_after = c_ulong(), c_ulong()
prop = c_void_p()
if SUCCESS == get_window_property(dpy, window,
prop_atom, 0, max_size, False, ANYPROPERTYTYPE,
byref(type_return), byref(format_return), byref(nitems),
byref(bytes_after), byref(prop)):
return nitems.value, prop
return -1, None
def get(self):
arg = DrmModeObjGetPropertiesC()
arg.obj_id = self.obj_id
arg.obj_type = self.obj_type
fcntl.ioctl(self._drm.fd, DRM_IOCTL_MODE_OBJ_GETPROPERTIES, arg)
prop_ids = (ctypes.c_uint32*arg.count_props)()
arg.props_ptr = ctypes.cast(ctypes.pointer(prop_ids), ctypes.c_void_p).value
prop_values = (ctypes.c_uint64*arg.count_props)()
arg.prop_values_ptr = ctypes.cast(ctypes.pointer(prop_values), ctypes.c_void_p).value
fcntl.ioctl(self._drm.fd, DRM_IOCTL_MODE_OBJ_GETPROPERTIES, arg)
self._arg = arg
vals = [v for i, v in zip(prop_ids, prop_values) if i == self.id]
return vals[0]
def set(self, fb, x, y, mode, *conns):
arg = DrmModeCrtcC()
arg.crtc_id = self.id
arg.fb_id = fb.id
arg.x = x
arg.y = y
arg.mode_valid = 1
arg.mode = mode._arg
connector_ids = (ctypes.c_uint32 * len(conns))(*[conn.id for conn in conns])
arg.set_connectors_ptr = ctypes.cast(ctypes.pointer(connector_ids), ctypes.c_void_p).value
arg.count_connectors = len(conns)
fcntl.ioctl(self._drm.fd, DRM_IOCTL_MODE_SETCRTC, arg)
self.fetch()
def command_detach(self):
detach_threads()
# unload debugger DLL
global debugger_dll_handle
if debugger_dll_handle is not None:
k32 = ctypes.WinDLL('kernel32')
k32.FreeLibrary.argtypes = [ctypes.c_void_p]
k32.FreeLibrary(debugger_dll_handle)
debugger_dll_handle = None
with _SendLockCtx:
write_bytes(conn, DETC)
detach_process()
for callback in DETACH_CALLBACKS:
callback()
raise DebuggerExitException()
def command_detach(self):
detach_threads()
# unload debugger DLL
global debugger_dll_handle
if debugger_dll_handle is not None:
k32 = ctypes.WinDLL('kernel32')
k32.FreeLibrary.argtypes = [ctypes.c_void_p]
k32.FreeLibrary(debugger_dll_handle)
debugger_dll_handle = None
with _SendLockCtx:
write_bytes(conn, DETC)
detach_process()
for callback in DETACH_CALLBACKS:
callback()
raise DebuggerExitException()
def GetParentDeviceByType(device, parent_type):
""" Find the first parent of a device that implements the parent_type
@param IOService Service to inspect
@return Pointer to the parent type, or None if it was not found.
"""
# First, try to walk up the IOService tree to find a parent of this device that is a IOUSBDevice.
parent_type = parent_type.encode('mac_roman')
while IORegistryEntryGetName(device) != parent_type:
parent = ctypes.c_void_p()
response = iokit.IORegistryEntryGetParentEntry(
device,
"IOService".encode("mac_roman"),
ctypes.byref(parent))
# If we weren't able to find a parent for the device, we're done.
if response != 0:
return None
device = parent
return device
def GetIOServicesByType(service_type):
"""
returns iterator over specified service_type
"""
serial_port_iterator = ctypes.c_void_p()
iokit.IOServiceGetMatchingServices(
kIOMasterPortDefault,
iokit.IOServiceMatching(service_type.encode('mac_roman')),
ctypes.byref(serial_port_iterator))
services = []
while iokit.IOIteratorIsValid(serial_port_iterator):
service = iokit.IOIteratorNext(serial_port_iterator)
if not service:
break
services.append(service)
iokit.IOObjectRelease(serial_port_iterator)
return services
def rawaddressof(self, BTypePtr, cdata, offset=None):
if isinstance(cdata, CTypesBaseStructOrUnion):
ptr = ctypes.pointer(type(cdata)._to_ctypes(cdata))
elif isinstance(cdata, CTypesGenericPtr):
if offset is None or not issubclass(type(cdata)._BItem,
CTypesBaseStructOrUnion):
raise TypeError("unexpected cdata type")
ptr = type(cdata)._to_ctypes(cdata)
elif isinstance(cdata, CTypesGenericArray):
ptr = type(cdata)._to_ctypes(cdata)
else:
raise TypeError("expected a <cdata 'struct-or-union'>")
if offset:
ptr = ctypes.cast(
ctypes.c_void_p(
ctypes.cast(ptr, ctypes.c_void_p).value + offset),
type(ptr))
return BTypePtr._from_ctypes(ptr)
def get_page(self, index):
""" Return the sub-bitmap for the given page index.
Please close the returned bitmap when done.
"""
with self._fi as lib:
# Create low-level bitmap in freeimage
bitmap = lib.FreeImage_LockPage(self._bitmap, index)
bitmap = ctypes.c_void_p(bitmap)
if not bitmap: # pragma: no cover
raise ValueError('Could not open sub-image %i in %r: %s' %
(index, self._filename,
self._fi._get_error_message()))
# Get bitmap object to wrap this bitmap
bm = FIBitmap(self._fi, self._filename, self._ftype, self._flags)
bm._set_bitmap(bitmap, (lib.FreeImage_UnlockPage, self._bitmap,
bitmap, False))
return bm
def add(self, ref, pred):
if not isinstance(ref, torch.IntTensor):
raise TypeError('ref must be a torch.IntTensor (got {})'
.format(type(ref)))
if not isinstance(pred, torch.IntTensor):
raise TypeError('pred must be a torch.IntTensor(got {})'
.format(type(pred)))
assert self.unk > 0, 'unknown token index must be >0'
rref = ref.clone()
rref.apply_(lambda x: x if x != self.unk else -x)
rref = rref.contiguous().view(-1)
pred = pred.contiguous().view(-1)
C.bleu_add(
ctypes.byref(self.stat),
ctypes.c_size_t(rref.size(0)),
ctypes.c_void_p(rref.data_ptr()),
ctypes.c_size_t(pred.size(0)),
ctypes.c_void_p(pred.data_ptr()),
ctypes.c_int(self.pad),
ctypes.c_int(self.eos))
def all_reduce(input, output=None, op=SUM, stream=None):
comm = communicator()
if output is None:
output = input
if stream is not None:
stream = stream.cuda_stream
data_type = nccl_types[input.type()]
check_error(lib.ncclAllReduce(
ctypes.c_void_p(input.data_ptr()),
ctypes.c_void_p(output.data_ptr()),
ctypes.c_size_t(input.numel()),
data_type,
op,
comm,
ctypes.c_void_p(stream)))
return output
def GetParentDeviceByType(device, parent_type):
""" Find the first parent of a device that implements the parent_type
@param IOService Service to inspect
@return Pointer to the parent type, or None if it was not found.
"""
# First, try to walk up the IOService tree to find a parent of this device that is a IOUSBDevice.
parent_type = parent_type.encode('mac_roman')
while IORegistryEntryGetName(device) != parent_type:
parent = ctypes.c_void_p()
response = iokit.IORegistryEntryGetParentEntry(
device,
"IOService".encode("mac_roman"),
ctypes.byref(parent))
# If we weren't able to find a parent for the device, we're done.
if response != 0:
return None
device = parent
return device
def GetIOServicesByType(service_type):
"""
returns iterator over specified service_type
"""
serial_port_iterator = ctypes.c_void_p()
iokit.IOServiceGetMatchingServices(
kIOMasterPortDefault,
iokit.IOServiceMatching(service_type.encode('mac_roman')),
ctypes.byref(serial_port_iterator))
services = []
while iokit.IOIteratorIsValid(serial_port_iterator):
service = iokit.IOIteratorNext(serial_port_iterator)
if not service:
break
services.append(service)
iokit.IOObjectRelease(serial_port_iterator)
return services
def AllocateEnv():
if pooling:
ret = ODBC_API.SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_CONNECTION_POOLING, SQL_CP_ONE_PER_HENV, SQL_IS_UINTEGER)
check_success(SQL_NULL_HANDLE, ret)
'''
Allocate an ODBC environment by initializing the handle shared_env_h
ODBC enviroment needed to be created, so connections can be created under it
connections pooling can be shared under one environment
'''
global shared_env_h
shared_env_h = ctypes.c_void_p()
ret = ODBC_API.SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, ADDR(shared_env_h))
check_success(shared_env_h, ret)
# Set the ODBC environment's compatibil leve to ODBC 3.0
ret = ODBC_API.SQLSetEnvAttr(shared_env_h, SQL_ATTR_ODBC_VERSION, SQL_OV_ODBC3, 0)
check_success(shared_env_h, ret)
def win_create_mdb(mdb_path, sort_order = "General\0\0"):
if sys.platform not in ('win32','cli'):
raise Exception('This function is available for use in Windows only.')
mdb_driver = [d for d in drivers() if 'Microsoft Access Driver (*.mdb' in d]
if mdb_driver == []:
raise Exception('Access Driver is not found.')
else:
driver_name = mdb_driver[0].encode('mbcs')
#CREATE_DB=<path name> <sort order>
ctypes.windll.ODBCCP32.SQLConfigDataSource.argtypes = [ctypes.c_void_p,ctypes.c_ushort,ctypes.c_char_p,ctypes.c_char_p]
if py_v3:
c_Path = bytes("CREATE_DB=" + mdb_path + " " + sort_order,'mbcs')
else:
c_Path = "CREATE_DB=" + mdb_path + " " + sort_order
ODBC_ADD_SYS_DSN = 1
ret = ctypes.windll.ODBCCP32.SQLConfigDataSource(None,ODBC_ADD_SYS_DSN,driver_name, c_Path)
if not ret:
raise Exception('Failed to create Access mdb file - "%s". Please check file path, permission and Access driver readiness.' %mdb_path)
def win_compact_mdb(mdb_path, compacted_mdb_path, sort_order = "General\0\0"):
if sys.platform not in ('win32','cli'):
raise Exception('This function is available for use in Windows only.')
mdb_driver = [d for d in drivers() if 'Microsoft Access Driver (*.mdb' in d]
if mdb_driver == []:
raise Exception('Access Driver is not found.')
else:
driver_name = mdb_driver[0].encode('mbcs')
#COMPACT_DB=<source path> <destination path> <sort order>
ctypes.windll.ODBCCP32.SQLConfigDataSource.argtypes = [ctypes.c_void_p,ctypes.c_ushort,ctypes.c_char_p,ctypes.c_char_p]
#driver_name = "Microsoft Access Driver (*.mdb)"
if py_v3:
c_Path = bytes("COMPACT_DB=" + mdb_path + " " + compacted_mdb_path + " " + sort_order,'mbcs')
#driver_name = bytes(driver_name,'mbcs')
else:
c_Path = "COMPACT_DB=" + mdb_path + " " + compacted_mdb_path + " " + sort_order
ODBC_ADD_SYS_DSN = 1
ret = ctypes.windll.ODBCCP32.SQLConfigDataSource(None,ODBC_ADD_SYS_DSN,driver_name, c_Path)
if not ret:
raise Exception('Failed to compact Access mdb file - "%s". Please check file path, permission and Access driver readiness.' %compacted_mdb_path)