def init():
global pa, in_stream, out_stream, error
error = ctypes.c_int(0)
pa = ctypes.cdll.LoadLibrary('libpulse-simple.so.0')
pa.strerror.restype = ctypes.c_char_p
ss = _struct_pa_sample_spec(_PA_SAMPLE_S16LE, 16000, 1)
out_stream = ctypes.c_void_p(pa.pa_simple_new(None,
'Alexa'.encode('ascii'), _PA_STREAM_PLAYBACK, None,
'Alexa voice'.encode('ascii'), ctypes.byref(ss),
None, None, ctypes.byref(error)))
if not out_stream:
raise Exception('Could not create pulse audio output stream: '
+ str(pa.strerror(error), 'ascii'))
in_stream = ctypes.c_void_p(pa.pa_simple_new(None,
'Alexa'.encode('ascii'), _PA_STREAM_RECORD, None,
'Alexa mic'.encode('ascii'), ctypes.byref(ss),
None, None, ctypes.byref(error)))
if not in_stream:
raise Exception('Could not create pulse audio input stream: '
+ str(pa.strerror(error), 'ascii'))
logging.info('PulseAudio is initialized.')
python类c_void_p()的实例源码
def draw_primitive(primitive, gltf,
modelview_matrix=None,
projection_matrix=None,
view_matrix=None,
normal_matrix=None):
set_draw_state(primitive, gltf,
modelview_matrix=modelview_matrix,
projection_matrix=projection_matrix,
view_matrix=view_matrix,
normal_matrix=normal_matrix)
index_accessor = gltf['accessors'][primitive['indices']]
index_bufferView = gltf['bufferViews'][index_accessor['bufferView']]
gl.glBindBuffer(index_bufferView['target'], index_bufferView['id'])
gl.glDrawElements(primitive['mode'], index_accessor['count'], index_accessor['componentType'],
c_void_p(index_accessor['byteOffset']))
global num_draw_calls
num_draw_calls += 1
if CHECK_GL_ERRORS:
if gl.glGetError() != gl.GL_NO_ERROR:
raise Exception('error drawing elements')
def draw_text(self, text, color=(1.0, 1.0, 1.0, 0.0),
view_matrix=None, projection_matrix=None):
gl.glUseProgram(self._program_id)
gl.glActiveTexture(gl.GL_TEXTURE0+0)
gl.glBindTexture(gl.GL_TEXTURE_2D, self._texture_id)
gl.glBindSampler(0, self._sampler_id)
gl.glUniform1i(self._uniform_locations['u_fonttex'], 0)
gl.glUniform4f(self._uniform_locations['u_color'], *color)
if view_matrix is not None:
self._matrix.dot(view_matrix, out=self._modelview_matrix)
gl.glUniformMatrix4fv(self._uniform_locations['u_modelviewMatrix'], 1, False, self._modelview_matrix)
if projection_matrix is not None:
gl.glUniformMatrix4fv(self._uniform_locations['u_projectionMatrix'], 1, False, projection_matrix)
gl.glEnableVertexAttribArray(0)
gl.glEnableVertexAttribArray(1)
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
x = 0.0
text = [ord(c) - 32 for c in text]
for i in text:
if i >= 0 and i < 95:
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._buffer_ids[i])
gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, False, 0, c_void_p(0))
gl.glVertexAttribPointer(1, 2, gl.GL_FLOAT, False, 0, c_void_p(8*4))
gl.glUniform1f(self._uniform_locations['advance'], x)
gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)
x += self._advance[i]
gl.glDisableVertexAttribArray(0)
gl.glDisableVertexAttribArray(1)
gl.glDisable(gl.GL_BLEND)
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_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 get_global(self, name, typ):
'''Return a global address'''
addr = self.engine.get_global_value_address(name)
ptr = ct.cast(ct.c_void_p(addr), typ)
return ptr
# Runtime configuration #####################################################
def to_rain(self, val):
if isinstance(val, (list, tuple)):
table_box = T.cbox.to_rain(None)
self.rain_set_table(table_box)
meta_ptr = self.get_global('core.types.array.module', T.carg)
self.rain_set_env(table_box, meta_ptr)
for i, n in enumerate(val):
self.rain_put_py(table_box, i, self.to_rain(n))
return table_box
elif isinstance(val, A.node):
table_box = T.cbox.to_rain(None)
self.rain_set_table(table_box)
ast_ptr = self.get_global('core.ast.module', T.carg)
meta_ptr = self.rain_get_ptr_py(ast_ptr, val.__tag__)
if not ct.cast(meta_ptr, ct.c_void_p).value:
Q.abort('Unable to look up core.ast.{}'.format(val.__tag__))
self.rain_set_env(table_box, meta_ptr)
slots = [self.to_rain(getattr(val, key, None)) for key in val.__slots__]
for key, box in zip(val.__slots__, slots):
self.rain_put_py(table_box, key, box)
return table_box
elif isinstance(val, K.value_token):
return T.cbox.to_rain(val.value)
return T.cbox.to_rain(val)
def __str__(self):
env_p = ct.cast(self.env, ct.c_void_p).value or 0
return 'cbox({}, {}, 0x{:08x}, 0x{:08x})'.format(self.type, self.size, self.data, env_p)
def _copyData(self, archiveR, archiveW):
''' '''
r = ctypes.c_int()
buff = ctypes.c_void_p()
size = ctypes.c_int()
offs = ctypes.c_longlong()
while True:
# Read in a block
r = self._readDataBlock(
archiveR, # Archive (reading)
ctypes.byref(buff), # Buffer pointer
ctypes.byref(size), # Size pointer
ctypes.byref(offs)) # Offset pointer
# Check ourselves
if r == self.ARCH_EOF:
return self.ARCH_OK
if r != self.ARCH_OK:
return r
# Write out a block
r = self._writeDataBlock(
archiveW, # Archive (writing)
buff, # Buffer data
size, # Size data
offs) # Offset data
# And check ourselves again
if r != self.ARCH_OK:
print(self._errorString(archiveB))
return r
def hotpatch(source, destination):
source = cast(source, c_void_p).value
destination = cast(destination, c_void_p).value
old = DWORD()
if windll.kernel32.VirtualProtect(source - 5, 8, PAGE_EXECUTE_READWRITE, byref(old)):
try:
written = c_size_t()
jmp_code = struct.pack('<BI', 0xE9, (destination - source) & 0xFFFFFFFF)
windll.kernel32.WriteProcessMemory(-1, source - 5, cast(jmp_code, c_char_p), len(jmp_code), byref(written))
windll.kernel32.WriteProcessMemory(-1, source, cast(struct.pack('<H', 0xF9EB), c_char_p), 2, byref(written))
finally:
windll.kernel32.VirtualProtect(source - 5, 8, old, byref(old))
return source + 2
def unhotpatch(source):
source = cast(source, c_void_p).value
old = DWORD()
if windll.kernel32.VirtualProtect(source, 2, PAGE_EXECUTE_READWRITE, byref(old)):
try:
written = c_size_t()
windll.kernel32.WriteProcessMemory(-1, source, cast(b'\x8B\xFF', c_char_p), 2, byref(written))
finally:
windll.kernel32.VirtualProtect(source, 2, old, byref(old))
def _unwrap_window_id(window_id):
try:
return int(window_id)
except:
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object]
return int(ctypes.pythonapi.PyCapsule_GetPointer(window_id, None))
def _addr_repr(self, address):
if address == 0:
return 'NULL'
else:
if address < 0:
address += 1 << (8*ctypes.sizeof(ctypes.c_void_p))
return '0x%x' % address
def _from_ctypes(cls, ctypes_ptr):
address = ctypes.cast(ctypes_ptr, ctypes.c_void_p).value or 0
return cls._new_pointer_at(address)
def handler(exc):
print("==Entry of VEH handler==")
if exc[0].ExceptionRecord[0].ExceptionCode == EXCEPTION_ACCESS_VIOLATION:
target_addr = ctypes.cast(exc[0].ExceptionRecord[0].ExceptionInformation[1], ctypes.c_void_p).value
print("Instr at {0} accessed to addr {1}".format(hex(exc[0].ExceptionRecord[0].ExceptionAddress), hex(target_addr)))
print("Resetting page protection to <PAGE_READWRITE>")
windows.winproxy.VirtualProtect(target_page, 0x1000, windef.PAGE_READWRITE)
exc[0].ContextRecord[0].EEFlags.TF = 1
return windef.EXCEPTION_CONTINUE_EXECUTION
else:
print("Exception of type {0}".format(exc[0].ExceptionRecord[0].ExceptionCode))
print("Resetting page protection to <PAGE_NOACCESS>")
windows.winproxy.VirtualProtect(target_page, 0x1000, windef.PAGE_NOACCESS)
return windef.EXCEPTION_CONTINUE_EXECUTION
def ptr_flink_to_remote_module(self, ptr_value):
return RemoteLoadedModule(ptr_value - ctypes.sizeof(ctypes.c_void_p) * 2, self._target)
def try_generate_stub_target(shellcode, argument_buffer, target, errcheck=None):
if not windows.current_process.is_wow_64:
raise ValueError("Calling execute_64bits_code_from_syswow from non-syswow process")
native_caller = generate_64bits_execution_stub_from_syswow(shellcode)
native_caller.errcheck = errcheck if errcheck is not None else target.errcheck
# Generate the wrapper function that fill the argument_buffer
expected_arguments_number = len(target.prototype._argtypes_)
def wrapper(*args):
if len(args) != expected_arguments_number:
raise ValueError("{0} syswow accept {1} args ({2} given)".format(target.__name__, expected_arguments_number, len(args)))
# Transform args (ctypes byref possibly) to int
writable_args = []
for i, value in enumerate(args):
if not isinstance(value, (int, long)):
try:
value = ctypes.cast(value, ctypes.c_void_p).value
except ctypes.ArgumentError as e:
raise ctypes.ArgumentError("Argument {0}: wrong type <{1}>".format(i, type(value).__name__))
writable_args.append(value)
# Build buffer
buffer = struct.pack("<" + "Q" * len(writable_args), *writable_args)
ctypes.memmove(argument_buffer, buffer, len(buffer))
# Copy origincal args in function, for errcheck if needed
native_caller.current_original_args = args # TODO: THIS IS NOT THREAD SAFE
return native_caller()
wrapper.__name__ = "{0}<syswow64>".format(target.__name__,)
wrapper.__doc__ = "This is a wrapper to {0} in 64b mode, it accept <{1}> args".format(target.__name__, expected_arguments_number)
return wrapper
def transform_arguments(self, types):
res = []
for type in types:
if type in (ctypes.c_wchar_p, ctypes.c_char_p):
res.append(ctypes.c_void_p)
else:
res.append(type)
return res
def raw_value(self):
return ctypes.cast(self, ctypes.c_void_p).value
def _create_vtable(self, interface):
implems = []
names = []
for index, name, method in self.extract_methods_order(interface):
func_implem = getattr(self, name)
#PVOID is 'this'
types = [method.restype, PVOID] + list(method.argtypes)
implems.append(ctypes.WINFUNCTYPE(*types)(func_implem))
names.append(name)
class Vtable(ctypes.Structure):
_fields_ = [(name, ctypes.c_void_p) for name in names]
return Vtable(*[ctypes.cast(x, ctypes.c_void_p) for x in implems]), implems