Example #1
0
    def close(self):
        import _ctypes
        fn = self.lib.lt_close_env
        fn.argtypes = [POINTER(SN_env)]
        fn(self.env)

        _ctypes.dlclose(self.lib._handle)
Example #2
0
 def close(self):
     if self.system == 'windows':
         _ctypes.FreeLibrary(self.kunpeng._handle)
     else:
         handle = self.kunpeng._handle
         del self.kunpeng
         _ctypes.dlclose(handle)
Example #3
0
    def close(self):

        # unload the models on the C++ side
        _unload_models = self.libptr.unload_models
        _unload_models.restype = None
        _unload_models.argtypes = [c.c_void_p]
        self.libptr.unload_models(self._zpar_session_obj)

        # clean up the data structures on the python side
        if self.tagger:
            self.tagger.cleanup()

        if self.parser:
            self.parser.cleanup()

        if self.depparser:
            self.depparser.cleanup()

        # set all the fields to none to enable clean reuse
        self.tagger = None
        self.parser = None
        self.depparser = None
        self.modelpath = None

        # clean up the CDLL object too so that upon reuse, we get a new one
        _ctypes.dlclose(self.libptr._handle)
        # pretty sure once the old object libptr was pointed to should
        # get garbage collected at some point after this
        self.libptr = None
        self._zpar_session_obj = None
Example #4
0
    def __del__(self):

        if self._lib and self._fd:
            self._lib.uinput_destroy(self._fd)
            self._fd = None
            _ctypes.dlclose(self._lib._handle)
            self._lib = None
def g2ToFile_nostreams(folder_name, file_out_name, max_time, bin_width,
                       pulse_spacing, max_pulse_distance):
    file_list = os.listdir(folder_name)
    int_bin_width = round(bin_width / tagger_resolution) * tagger_resolution
    int_max_time = round(max_time / int_bin_width) * int_bin_width
    int_pulse_spacing = round(pulse_spacing / int_bin_width) * int_bin_width
    max_bin = int(round(int_max_time / int_bin_width))
    num_files = len(file_list)
    numer_list = [int(0)] * (2 * max_bin + 1)
    denom_ctypes = ctypes.c_int(0)
    ctypes_file_list = file_list_to_ctypes(file_list, folder_name)
    lib = ctypes.CDLL(working_directory + '/' + lib_name)
    lib.getG2Correlations_nostreams.argtypes = [
        ctypes.c_char_p * num_files, ctypes.c_int, ctypes.c_double,
        ctypes.c_double, ctypes.c_double, ctypes.c_int, ctypes.py_object,
        ctypes.POINTER(ctypes.c_int)
    ]
    start_time = time.time()
    #with wurlitzer.sys_pipes():
    lib.getG2Correlations_nostreams(ctypes_file_list, num_files, int_max_time,
                                    int_bin_width, int_pulse_spacing,
                                    max_pulse_distance, numer_list,
                                    ctypes.byref(denom_ctypes))
    print("Finished in " + str(time.time() - start_time) + "s")

    if os.name == 'nt':
        _ctypes.FreeLibrary(lib._handle)
    else:
        _ctypes.dlclose(lib._handle)
    tau = np.arange(-max_bin, max_bin + 1) * int_bin_width
    scipy.io.savemat(file_out_name, {
        'numer': np.array(numer_list),
        'denom': denom_ctypes.value,
        'tau': tau
    })
Example #6
0
    def __del__(self):

        if self._lib and self._fd:
            self._lib.uinput_destroy(self._fd)
            self._fd = None
            _ctypes.dlclose(self._lib._handle)
            self._lib = None
Example #7
0
    def close(self):
        import _ctypes
        fn = self.lib.lt_close_env
        fn.argtypes = [POINTER(SN_env)]
        fn(self.env)

        _ctypes.dlclose(self.lib._handle)
Example #8
0
def closeLibrary():
    import _ctypes

    if "FreeLibrary" in dir(_ctypes):
        _ctypes.FreeLibrary(ssl._lib._handle)
    else:
        _ctypes.dlclose(ssl._lib._handle)
Example #9
0
    def close(self):
        # unload the models on the C++ side
        self.libptr.unload_models()

        # clean up the data structures on the python side
        if self.tagger:
            self.tagger.cleanup()

        if self.parser:
            self.parser.cleanup()

        if self.depparser:
            self.depparser.cleanup()

        # set all the fields to none to enable clean reuse
        self.tagger = None
        self.parser = None
        self.depparser = None
        self.modelpath = None

        # clean up the CDLL object too so that upon reuse, we get a new one
        _ctypes.dlclose(self.libptr._handle)
        # pretty sure once the old object libptr was pointed to should
        # get garbage collected at some point after this
        self.libptr = None
Example #10
0
 def cleanup_lib(self):
     """ unload the previously loaded shared library """
     if not self.using_openmp:
         #this if statement is necessary because shared libraries that use
         #OpenMP will core dump when unloaded, this is a well-known issue with OpenMP
         logging.debug('unloading shared library')
         _ctypes.dlclose(self.lib._handle)
Example #11
0
def reload_library(lib):
    handle = lib._handle
    name = lib._name
    del lib
    while is_loaded(name):
        _ctypes.dlclose(handle)
    return ctypes.cdll.LoadLibrary(name)
Example #12
0
 def close(self):
     if self.compiled is not None:
         self.compiled = None
         gc.collect()
         dlclose(self.handle)
         self.handle = None
         gc.collect()
Example #13
0
 def cleanup_lib(self):
     """ unload the previously loaded shared library """
     if not self.using_openmp:
         #this if statement is necessary because shared libraries that use
         #OpenMP will core dump when unloaded, this is a well-known issue with OpenMP
         logging.debug('unloading shared library')
         _ctypes.dlclose(self.lib._handle)
Example #14
0
def check_instruction(test_name, exec_name):
    if args.instruction_check and test_name in variables.test_to_enable_symbol_dict:
        symbol_name = variables.test_to_enable_symbol_dict[test_name]
        if symbol_name:
            lib = ctypes.cdll.LoadLibrary(exec_name)
            # Raise AttributeError if symbol undefined
            symbol = getattr(lib, symbol_name)
            _ctypes.dlclose(lib._handle)
Example #15
0
def dlclose(obj):
    """
    Close/unload a PIE binary or a shared library.
    :param obj: object returned by ctypes.CDLL when the resource was loaded
    """
    if platform == "win32":
        _ctypes.FreeLibrary(obj._handle)  # pylint:disable=protected-access,no-member
    else:
        _ctypes.dlclose(obj._handle)  # pylint:disable=protected-access,no-member
Example #16
0
def unload_library(name):
    if os.name != 'nt':
        """
        Don't unload the library on windows, as it may result in a crash when
        this gets really unloaded.
        """
        if name in _library_cache:
            dlclose(_library_cache[name]._handle)
            del _library_cache[name]
Example #17
0
def unload_library(name):
    if os.name != 'nt':
        """
        Don't unload the library on windows, as it may result in a crash when
        this gets really unloaded.
        """
        if name in _library_cache:
            dlclose(_library_cache[name]._handle)
            del _library_cache[name]
Example #18
0
 def __del__(self):
     if self._DlibraryHandle is not None:
         if self.port is not None:
             try:
                 self.Close()
             except:
                 raise YaPySerialError("Could'n t close serial port!")
         dlclose(self._DlibraryHandle)
         self._DlibraryHandle = None
         self.DlibraryHandle = None
Example #19
0
def close_dll(dll):
    """Closes dewesoft dll"""

    result = dll.DWDeInit()
    if result != DWStatus.DWSTAT_OK.value:
        raise RuntimeError("DWDeInit() failed: {}".format(result))
    if platform.system() == 'Windows':
        _ctypes.FreeLibrary(dll._handle)
    else:
        _ctypes.dlclose(dll._handle)
Example #20
0
 def freeLibrary(self):
     """ Call FMU destructor before being destructed. Just cleaning up. """
     if hasattr(self, "_library"):
         self.freeModelInstance()
         if platform.system() == "Linux":
             _ctypes.dlclose(self._libraryHandle)
         elif platform.system() == "Windows":
             _ctypes.FreeLibrary(self._libraryHandle)  # only for windows
         else:
             raise FMUError.FMUError("Unknown platform: %s\n" % platform.system())
Example #21
0
 def unload(self, plugin):
     filepath = plugin.file
     cdll = plugin.cdll
     self.unregister(plugin)
     if cdll:
         if platform.system() == 'Windows':
             _ctypes.FreeLibrary(cdll._handle)
         else:
             _ctypes.dlclose(cdll._handle)
     return filepath
Example #22
0
 def __del__(self):
     if self._DlibraryHandle is not None:
         if self.port is not None:
             try:
                 self.Close()
             except:
                 raise YaPySerialError("Could'n t close serial port!")
         dlclose(self._DlibraryHandle)
         self._DlibraryHandle = None
         self.DlibraryHandle = None
Example #23
0
def closeLibrary():
    handle = ssl._lib._handle
    if "FreeLibrary" in dir(_ctypes):
        _ctypes.FreeLibrary(handle)
        _ctypes.FreeLibrary(handle)
        print "OpenSSL closed, handle:", handle
    else:
        _ctypes.dlclose(handle)
        _ctypes.dlclose(handle)
        print "OpenSSL dlclosed, handle:", handle
Example #24
0
 def __del__(self):
     import sys
     from _ctypes import dlclose
     # XXX fish fish fish
     mod = self.__dict__['mod']
     dlclose(mod._lib._handle)
     try:
         del sys.modules[mod.__name__]
     except KeyError:
         pass
Example #25
0
def closeLibrary():
    handle = ssl._lib._handle
    if "FreeLibrary" in dir(_ctypes):
        _ctypes.FreeLibrary(handle)
        _ctypes.FreeLibrary(handle)
        print "OpenSSL closed, handle:", handle
    else:
        _ctypes.dlclose(handle)
        _ctypes.dlclose(handle)
        print "OpenSSL dlclosed, handle:", handle
Example #26
0
def set_function_pointers(acados, model_name, user_fun_name, acados_ext_fun):

    #	print(user_fun_name)

    # generate function pointers getter
    generate_getter(user_fun_name)

    # compile and load shared library
    model_getter_name = user_fun_name + '_getter.so'
    #	model_getter_name = 'fun_getter.so' # XXX it needs an unique name !!!
    system('gcc -fPIC -shared casadi_fun_ptr_getter.c -o ' +
           model_getter_name + ' -L. ' + model_name)
    #	print(model_name)
    #	system('nm ' + model_name)
    model_getter = CDLL(model_getter_name)

    # set up function pointers
    model_getter.get_fun_fun.restype = c_void_p
    tmp_ptr = model_getter.get_fun_fun()
    #	print(tmp_ptr)
    acados.external_function_casadi_set_fun.argtypes = [c_void_p, c_void_p]
    acados.external_function_casadi_set_fun(acados_ext_fun, tmp_ptr)

    model_getter.get_fun_work.restype = c_void_p
    tmp_ptr = model_getter.get_fun_work()
    acados.external_function_casadi_set_work.argtypes = [c_void_p, c_void_p]
    acados.external_function_casadi_set_work(acados_ext_fun, tmp_ptr)

    model_getter.get_fun_sparsity_in.restype = c_void_p
    tmp_ptr = model_getter.get_fun_sparsity_in()
    acados.external_function_casadi_set_sparsity_in.argtypes = [
        c_void_p, c_void_p
    ]
    acados.external_function_casadi_set_sparsity_in(acados_ext_fun, tmp_ptr)

    model_getter.get_fun_sparsity_out.restype = c_void_p
    tmp_ptr = model_getter.get_fun_sparsity_out()
    acados.external_function_casadi_set_sparsity_out.argtypes = [
        c_void_p, c_void_p
    ]
    acados.external_function_casadi_set_sparsity_out(acados_ext_fun, tmp_ptr)

    model_getter.get_fun_n_in.restype = c_void_p
    tmp_ptr = model_getter.get_fun_n_in()
    acados.external_function_casadi_set_n_in.argtypes = [c_void_p, c_void_p]
    acados.external_function_casadi_set_n_in(acados_ext_fun, tmp_ptr)

    model_getter.get_fun_n_out.restype = c_void_p
    tmp_ptr = model_getter.get_fun_n_out()
    acados.external_function_casadi_set_n_out.argtypes = [c_void_p, c_void_p]
    acados.external_function_casadi_set_n_out(acados_ext_fun, tmp_ptr)

    _ctypes.dlclose(model_getter._handle)
    system('rm casadi_fun_ptr_getter.c')
    system('rm ' + model_getter_name)
Example #27
0
    def error_handling(self):
        time.sleep(0.001)
        handle = self._shared._handle
        #    dlclose(handle)
        while True:
            try:
                dlclose(handle)
            except:
                break

        self.__attach()
Example #28
0
 def freeLibrary(self):
     ''' Call FMU destructor before being destructed. Just cleaning up. '''
     if hasattr(self, '_library'):
         self.freeModelInstance()
         if platform.system() == 'Linux':
             _ctypes.dlclose(self._libraryHandle)
         elif platform.system() == 'Windows':
             _ctypes.FreeLibrary(self._libraryHandle)  #only for windows
         else:
             raise FMUError.FMUError('Unknown platform: %s\n' %
                                     platform.system())
Example #29
0
def g2ToFile_pulse(folder_name, file_out_name, min_tau_1, max_tau_1, min_tau_2,
                   max_tau_2, bin_width):
    file_list = os.listdir(folder_name)
    int_bin_width = round(bin_width / tagger_resolution) * tagger_resolution

    int_min_tau_1 = round(min_tau_1 / int_bin_width) * int_bin_width
    min_tau_1_bin = int(round(int_min_tau_1 / int_bin_width))

    int_min_tau_2 = round(min_tau_2 / int_bin_width) * int_bin_width
    min_tau_2_bin = int(round(int_min_tau_2 / int_bin_width))

    int_max_tau_1 = round(max_tau_1 / int_bin_width) * int_bin_width
    max_tau_1_bin = int(round(int_max_tau_1 / int_bin_width))

    int_max_tau_2 = round(max_tau_2 / int_bin_width) * int_bin_width
    max_tau_2_bin = int(round(int_max_tau_2 / int_bin_width))

    num_files = len(file_list)
    numer_list = [int(0)] * (max_tau_1_bin - min_tau_1_bin +
                             1) * (max_tau_2_bin - min_tau_2_bin + 1)

    denom_ctypes = ctypes.c_int(0)
    ctypes_file_list = file_list_to_ctypes(file_list, folder_name)
    lib = ctypes.CDLL(working_directory + '/' + lib_name)
    lib.getG2Correlations_pulse.argtypes = [
        ctypes.c_char_p * num_files, ctypes.c_int, ctypes.c_double,
        ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.c_double,
        ctypes.py_object,
        ctypes.POINTER(ctypes.c_int), ctypes.c_int
    ]
    start_time = time.time()
    #with wurlitzer.sys_pipes():
    lib.getG2Correlations_pulse(ctypes_file_list, num_files, int_min_tau_1,
                                int_max_tau_1, int_min_tau_2, int_max_tau_2,
                                int_bin_width, numer_list,
                                ctypes.byref(denom_ctypes), 4)
    print("Finished in " + str(time.time() - start_time) + "s")
    time.sleep(1)
    if os.name == 'nt':
        _ctypes.FreeLibrary(lib._handle)
    else:
        _ctypes.dlclose(lib._handle)
    tau_1 = np.arange(min_tau_1_bin, max_tau_1_bin + 1) * int_bin_width
    tau_2 = np.arange(min_tau_2_bin, max_tau_2_bin + 1) * int_bin_width
    scipy.io.savemat(
        file_out_name, {
            'numer':
            np.array(numer_list).reshape(max_tau_2_bin - min_tau_2_bin + 1,
                                         max_tau_1_bin - min_tau_1_bin + 1),
            'tau_1':
            tau_1,
            'tau_2':
            tau_2
        })
Example #30
0
 def __del__(self):
     """Handle removal of the DLL when the simulator is deleted."""
     if self._dll is not None:
         handle = self._dll._handle
         if platform.system() == 'Windows':
             _ctypes.FreeLibrary(handle)  # pylint: disable=no-member
         else:
             _ctypes.dlclose(handle)  # pylint: disable=no-member
         self._dll = None
     if self._dir is not None:
         shutil.rmtree(self._dir)
         self._dir = None
Example #31
0
 def release(self):
     # type: () -> None
     """
     Release any resources associated with the model.
     """
     dll_handle = self._dll._handle
     if os.name == 'nt':
         ct.windll.kernel32.FreeLibrary(dll_handle)
     else:
         _ct.dlclose(dll_handle)
     del self._dll
     self._dll = None
Example #32
0
    def __detach(self):
        try:
            self.command('quit')
        except:
            pass

        time.sleep(0.001)
        handle = self._shared._handle
        while True:
            try:
                dlclose(handle)
            except:
                break
Example #33
0
def unload(dss):

    library = dss.dss_lib

    if os.name == "nt":
        from ctypes import windll
        windll.kernel32.FreeLibrary(library._handle)
    else:
        while _isLoaded():
            import _ctypes
            _ctypes.dlclose(library._handle)

    _dss_delete(dss)
Example #34
0
def _unload_lib_obj(olib):
    if utils.is_windows():
        import _ctypes
        _ctypes.FreeLibrary(olib._handle)
        del olib
    elif utils.is_linux():
        import _ctypes
        _ctypes.dlclose(olib._handle)
        del olib
    elif utils.is_mac():
        import _ctypes
        _ctypes.dlclose(olib._handle)
        del olib
Example #35
0
 def __del__(self):
     import sys
     if sys.platform == "win32":
         from _ctypes import FreeLibrary as dlclose
     else:
         from _ctypes import dlclose
     # XXX fish fish fish
     mod = self.__dict__['mod']
     dlclose(mod._lib._handle)
     try:
         del sys.modules[mod.__name__]
     except KeyError:
         pass
Example #36
0
 def __del__(self):
     import sys
     if sys.platform == "win32":
         from _ctypes import FreeLibrary as dlclose
     else:
         from _ctypes import dlclose
     # XXX fish fish fish
     mod = self.__dict__['mod']
     dlclose(mod._lib._handle)
     try:
         del sys.modules[mod.__name__]
     except KeyError:
         pass
Example #37
0
def set_function_pointers(acados, model_name, user_fun_name, acados_ext_fun):
	
#	print(user_fun_name)

	# generate function pointers getter
	generate_getter(user_fun_name)

	# compile and load shared library
	model_getter_name = user_fun_name + '_getter.so'
#	model_getter_name = 'fun_getter.so' # XXX it needs an unique name !!!
	system('gcc -fPIC -shared casadi_fun_ptr_getter.c -o ' + model_getter_name + ' -L. ' + model_name)
#	print(model_name)
#	system('nm ' + model_name)
	model_getter = CDLL(model_getter_name)

	# set up function pointers
	model_getter.get_fun_fun.restype = c_void_p
	tmp_ptr = model_getter.get_fun_fun()
#	print(tmp_ptr)
	acados.external_function_casadi_set_fun.argtypes = [c_void_p, c_void_p]
	acados.external_function_casadi_set_fun(acados_ext_fun, tmp_ptr)

	model_getter.get_fun_work.restype = c_void_p
	tmp_ptr = model_getter.get_fun_work()
	acados.external_function_casadi_set_work.argtypes = [c_void_p, c_void_p]
	acados.external_function_casadi_set_work(acados_ext_fun, tmp_ptr)

	model_getter.get_fun_sparsity_in.restype = c_void_p
	tmp_ptr = model_getter.get_fun_sparsity_in()
	acados.external_function_casadi_set_sparsity_in.argtypes = [c_void_p, c_void_p]
	acados.external_function_casadi_set_sparsity_in(acados_ext_fun, tmp_ptr)

	model_getter.get_fun_sparsity_out.restype = c_void_p
	tmp_ptr = model_getter.get_fun_sparsity_out()
	acados.external_function_casadi_set_sparsity_out.argtypes = [c_void_p, c_void_p]
	acados.external_function_casadi_set_sparsity_out(acados_ext_fun, tmp_ptr)

	model_getter.get_fun_n_in.restype = c_void_p
	tmp_ptr = model_getter.get_fun_n_in()
	acados.external_function_casadi_set_n_in.argtypes = [c_void_p, c_void_p]
	acados.external_function_casadi_set_n_in(acados_ext_fun, tmp_ptr)

	model_getter.get_fun_n_out.restype = c_void_p
	tmp_ptr = model_getter.get_fun_n_out()
	acados.external_function_casadi_set_n_out.argtypes = [c_void_p, c_void_p]
	acados.external_function_casadi_set_n_out(acados_ext_fun, tmp_ptr)

	_ctypes.dlclose(model_getter._handle)
	system('rm casadi_fun_ptr_getter.c')
	system('rm ' + model_getter_name)
Example #38
0
def load_shared_lib(shared_lib_path: str) -> ctypes.CDLL:
    """
    Load a shared library using ctypes freeing the resource at end.
    """
    plugin_dll = ctypes.cdll.LoadLibrary(shared_lib_path)
    try:
        yield plugin_dll
    finally:
        if sys.platform == 'win32':
            from _ctypes import FreeLibrary
            FreeLibrary(plugin_dll._handle)
        else:
            from _ctypes import dlclose
            dlclose(plugin_dll._handle)
Example #39
0
def ctypes_integrate(ccode, ranges, tmpfolder='libs/', **kwargs):
    tmpfile = '{}{}'.format(tmpfolder, str(uuid.uuid4()))
    with open(tmpfile+'.c', 'w') as file:
        file.writelines(ccode)
    call(['gcc', '-shared', '-o', tmpfile+'.dylib', '-fPIC', tmpfile+'.c'])
    lib = ctypes.CDLL(tmpfile+'.dylib')
    lib.f.restype = ctypes.c_double
    lib.f.argtypes = (ctypes.c_int, ctypes.c_double)
    result = np.sum([nquad(lib.f, rng)[0] for rng in ranges])
    dlclose(lib._handle) # this is to release the lib, so we can import the new version
    try:
        os.remove(tmpfile+'.c') # clean up
        os.remove(tmpfile+'.dylib') # clean up
    except FileNotFoundError: pass
    return result
 def close(self):
     if self._lib is None:
         return
     try:
         import _ctypes
         if hasattr(_ctypes, 'dlclose'):
             _ctypes.dlclose(self._lib._handle)
         else:
             logger.warning(
                 'Cannot close shared library; Python implementation does not provide "_ctypes.dlclose"'
             )
     except Exception as e:
         logger.exception(e)
     finally:
         self._lib = None
Example #41
0
    def unloadchifhandle(lib):
        """Release a handle on the chif iLOrest library

        :param lib: The library handle provided by loading the chif library.
        :type lib: library handle.

        """
        try:
            libhandle = lib._handle
            if os.name == 'nt':
                windll.kernel32.FreeLibrary(None, handle=libhandle)
            else:
                dlclose(libhandle)
        except Exception:
            pass
Example #42
0
 def unload(self):
     global yaya
     if yaya:
         yaya.unload()
         # force Python to unload the library
         # else the next load would not function properly
         try:
             _ctypes.FreeLibrary(yaya._handle)
         except:
             pass
         try:
             _ctypes.dlclose(yaya._handle)
         except:
             pass
         yaya = cdll.LoadLibrary("libaya5.so")
Example #43
0
    def remove_lib(self):
        # Unload the currently loaded dynamic linked library to be secure
        if self._lib is not None:
            _ctypes.FreeLibrary(self._lib._handle) if platform == 'win32' else _ctypes.dlclose(self._lib._handle)
            del self._lib
            self._lib = None

        # deactivate the cleanup finalizers for the current set of files
        if self._cleanup_files is not None:
            self._cleanup_files.detach()

        if self._cleanup_lib is not None:
            self._cleanup_lib.detach()

        # If file already exists, pull new names. This is necessary on a Windows machine, because
        # Python's ctype does not deal in any sort of manner well with dynamic linked libraries on this OS.
        if path.isfile(self.lib_file):
            [remove(s) for s in [self.src_file, self.lib_file, self.log_file]]
            if MPI:
                mpi_comm = MPI.COMM_WORLD
                mpi_rank = mpi_comm.Get_rank()
                basename = path.join(get_cache_dir(), self._cache_key) if mpi_rank == 0 else None
                basename = mpi_comm.bcast(basename, root=0)
                basename = basename + "_%d" % mpi_rank
            else:
                basename = path.join(get_cache_dir(), "%s_0" % self._cache_key)

            self.src_file = "%s.c" % basename
            self.lib_file = "%s.%s" % (basename, 'dll' if platform == 'win32' else 'so')
            self.log_file = "%s.log" % basename
    def unloadChifHandle(self, lib):
        """Release a handle on the chif hprest library

        :param lib: The library handle provided by loading the chif library.
        :type lib: library handle.

        """
        try:
            libhandle = lib._handle

            if os.name == 'nt':
                windll.kernel32.FreeLibrary(None, handle=libhandle)
            else:
                dlclose(libhandle)
        except Exception:
            pass
Example #45
0
 def _load(self, name):
     loader = self._get_loader()
     
     #Unload on Windows first
     if os.name == 'nt':
         handle = _get_handle_by_name(name)
         if handle != 0:
             dlclose(handle)
     
     #Let ctypes find it
     try:
         return getattr(loader, name)
 
     #Bad luck, let's search on sys.path
     except OSError:
         return self._load_from_sys_path(loader, name)
 def close_devices(self):
     if self.devices_open:
         import _ctypes
         import gc
         self.pyaudio.Pa_Terminate()
         self.pypm.Pm_Terminate()
         for x in (self.pyaudio._handle, self.pypm._handle):
             if pydaw_util.IS_WINDOWS:
                 _ctypes.FreeLibrary(x)
             else:
                 _ctypes.dlclose(x)
         del self.pyaudio
         del self.pypm
         gc.collect()
         self.devices_open = False
         time.sleep(0.5)  # Give the kernel audio API time to close
     else:
         pass
Example #47
0
def so_test():
    
    # load dynamic-link library.
    sotest = cdll.LoadLibrary("./so/sointerface.so")
    
    # execute the function in linked library
    print (sotest.sum(1,2))
    
    # before reload, need to delete the dynamic-link library.
    dlclose(sotest._handle)
    # in win32: _ctypes.FreeLibrary(sotest._handle)
    del sotest
    
    # update the library
    os.system('make test2')
    #    time.sleep(1)
    
    # reload the updated library.
    sotest = cdll.LoadLibrary("./so/sointerface.so")
    
    # execute the function in updated library
    print (sotest.sum(1,2))
Example #48
0
	def __del__(self):
		
#		print('\nin descruction\n')
		if self.scheme=='erk':
			if self.sens_forw=='false':
				self.__acados.external_function_casadi_free(self.expl_ode_fun)
			else:
				self.__acados.external_function_casadi_free(self.expl_vde_for)
		if self.scheme=='irk':
			if self.sens_forw=='false':
				self.__acados.external_function_casadi_free(self.impl_ode_fun)
				self.__acados.external_function_casadi_free(self.impl_ode_fun_jac_x_xdot_z)
		self.__acados.sim_config_destroy(self.config)
		self.__acados.sim_dims_destroy(self.dims)
		self.__acados.sim_opts_destroy(self.opts)
		self.__acados.sim_out_destroy(self.sim_in)
		self.__acados.sim_in_destroy(self.sim_out)
		self.__acados.sim_solver_destroy(self.solver)
#		print(self.__model)
#		print(self.__model._handle)
		# on POSIX systems; on windows call FreeLibrary instead
#		print(self.__model._handle)
		_ctypes.dlclose(self.__model._handle)
Example #49
0
def compute_nustar(dom, potential, eta, Loss, M, nu_prev, eta_prev, t,
                   pid='0', tmpfolder='libs/', KL=None):
    """ Determines the normalizing nustar for the dual-averaging update """
    tmpfile = '{}{}'.format(tmpfolder, str(uuid.uuid4()))
    with open(tmpfile+'.c', 'w') as file:
        file.writelines(generate_ccode(dom, potential, eta, Loss))
    call(['gcc', '-shared', '-o', tmpfile+'.dylib', '-fPIC', tmpfile+'.c'])
    lib = ctypes.CDLL(tmpfile+'.dylib')
    lib.f.restype = ctypes.c_double
    lib.f.argtypes = (ctypes.c_int, ctypes.c_double)
    # compute the bounds for the root finding method for mu*
    if potential.isconvex():
        a = eta_prev/eta*nu_prev - M # this is a bound based on convexity of the potential
        b = eta_prev/eta*nu_prev + (eta_prev/eta-1)*t*M
    else:
        a = - Loss.max() - np.max(potential.phi_inv(1/dom.volume)/eta, 0) # this is (coarse) lower bound on nustar
        b = nu_prev + 50 # this is NOT CORRECT - a hack. Need to find conservative bound for nonconvex potentials
    try:
        if isinstance(dom, nBox) or isinstance(dom, UnionOfDisjointnBoxes):
            if isinstance(dom, nBox):
                ranges = [dom.bounds]
            elif isinstance(dom, UnionOfDisjointnBoxes):
                ranges = [nbox.bounds for nbox in dom.nboxes]
            if isinstance(potential, ExponentialPotential):
                # in this case we don't have to search for nustar, we can find it (semi-)explicitly
                integral = np.sum([nquad(lib.f, rng, [0])[0] for rng in ranges])
                nustar = np.log(integral)/eta
            else:
                f = lambda nu: np.sum([nquad(lib.f, rng, args=[nu],
                                             opts=[{'epsabs':1.49e-4, 'epsrel':1.49e-3}]*dom.n)[0]
                                       for rng in ranges]) - 1
                success = False
                while not success:
                    try:
                        nustar = brentq(f, a, b)
                        success = True
                    except ValueError:
                        print('WARINING: PROCESS {} HAS ENCOUNTERED f(a)!=f(b)!'.format(pid))
                        a, b = a - 20, b + 20

        elif isinstance(dom, DifferenceOfnBoxes):
            if isinstance(potential, ExponentialPotential):
                # in this case we don't have to search for nustar, we can find it (semi-)explicitly
                integral = (nquad(lib.f, dom.outer.bounds, [0])[0]
                            - np.sum([nquad(lib.f, nbox.bounds, args=[0],
                                      opts=[{'epsabs':1.49e-4, 'epsrel':1.49e-3}]*dom.n)[0] for nbox in dom.inner]))
                nustar = np.log(integral)/eta
            else:
                f = lambda nu: (nquad(lib.f, dom.outer.bounds, [nu], opts=[{'epsabs':1.49e-4, 'epsrel':1.49e-3}])[0]
                                - np.sum([nquad(lib.f, nbox.bounds, [nu])[0] for nbox in dom.inner]) - 1)
                success = False
                while not success:
                    try:
                        nustar = brentq(f, a, b)
                        success = True
                    except ValueError:
                        a, b = a - 20, b + 20
                        print('WARINING: PROCESS {} HAS ENCOUNTERED f(a)!=f(b)!'.format(pid))
        else:
            raise Exception('For now, domain must be an nBox or a UnionOfDisjointnBoxes!')
        if KL is not None: # Compute KL(x*,lambda)
            tmpfile_KL = '{}{}'.format(tmpfolder, str(uuid.uuid4()))
            with open(tmpfile_KL+'.c', 'w') as file:
                file.writelines(generate_ccode(dom, potential, eta, Loss, KL=True))
            try:
                call(['gcc', '-shared', '-o', tmpfile_KL+'.dylib', '-fPIC', tmpfile_KL+'.c'])
                lib_KL = ctypes.CDLL(tmpfile_KL+'.dylib')
                lib_KL.f.restype = ctypes.c_double
                lib_KL.f.argtypes = (ctypes.c_int, ctypes.c_double)
                KLval = np.sum([nquad(lib_KL.f, rng, args=[nustar],
                                      opts=[{'epsabs':1.49e-6, 'epsrel':1.49e-6}]*dom.n)[0]
                                for rng in ranges])
                KL.append(KLval)
            finally:
                dlclose(lib_KL._handle)
                del lib_KL
                try:
                    os.remove(tmpfile_KL+'.c') # clean up
                    os.remove(tmpfile_KL+'.dylib') # clean up
                except FileNotFoundError: pass
        return nustar
    finally:
        dlclose(lib._handle) # this is to release the lib, so we can import the new version
        del lib # can this fix our memory leak?
        try:
            os.remove(tmpfile+'.c') # clean up
            os.remove(tmpfile+'.dylib') # clean up
        except FileNotFoundError: pass
Example #50
0
 def unload_plugin():
     dlclose(lib._handle)
Example #51
0
 def deleteCB(self, offset):
     """Free the state associated to @offset and delete it
     @offset: gcc state offset
     """
     _ctypes.dlclose(self.states[offset]._handle)
     del self.states[offset]
Example #52
0
 def unload_library(self, tdll):
     dlclose(tdll._handle)