Example #1
0
def find_libRgraphapp(rhome):
    libRdir = os.path.join(rhome, "bin",
                           "x64" if sys.maxsize > 2**32 else "i386")
    libRgraphapppath = os.path.join(libRdir, "Rgraphapp.dll")

    if not os.path.exists(libRgraphapppath):
        raise RuntimeError("Cannot locate Rgraphapp share library.")

    if RTLD_GLOBAL:
        return PyDLL(str(libRgraphapppath), mode=RTLD_GLOBAL)
    else:
        return PyDLL(str(libRgraphapppath))
def comtypes_to_pywin(ptr, interface=None):
    _PyCom_PyObjectFromIUnknown = PyDLL(pythoncom.__file__).PyCom_PyObjectFromIUnknown
    _PyCom_PyObjectFromIUnknown.restype = py_object

    if interface is None:
        interface = IUnknown
    return _PyCom_PyObjectFromIUnknown(ptr, byref(interface._iid_), True)
Example #3
0
 def init():
     rs_lib_path = util.find_library('rtipyroutingserviced')
     if rs_lib_path is None:
         raise ImportError('RoutingService native library not found.')
     rs_lib = PyDLL(rs_lib_path)
     if rs_lib.PyService_load() != 0:
         print(sys.last_value)
Example #4
0
def load_libR(rhome):
    if sys.platform.startswith("win"):
        libRdir = os.path.join(rhome, "bin",
                               "x64" if sys.maxsize > 2**32 else "i386")
        libRpath = os.path.join(libRdir, "R.dll")
    elif sys.platform == "darwin":
        libRpath = os.path.join(rhome, "lib", "libR.dylib")
    else:
        libRpath = os.path.join(rhome, "lib", "libR.so")

    if not os.path.exists(libRpath):
        raise RuntimeError("Cannot locate R share library.")

    if RTLD_GLOBAL:
        return PyDLL(str(libRpath), mode=RTLD_GLOBAL)
    else:
        return PyDLL(str(libRpath))
    def __init__(self, engine: str, logger=None) -> None:

        # Provide a default logger, if None provided
        if logger is None:
            logger = logging.getLogger('OpenEarthBMI')

        self.logger = logger

        # Assume C++ DLL with Python C API (i.e. Python.h)
        self.dll = dll = PyDLL(engine)

        # cache properties here
        self._implemented = {}  # {name: bool or None}

        class Level(IntEnum):
            LEVEL_ALL = 0
            LEVEL_DEBUG = 1
            LEVEL_INFO = 2
            LEVEL_WARNING = 3
            LEVEL_ERROR = 4
            LEVEL_FATAL = 5
            LEVEL_NONE = 6

        # typedef void (CALLCONV *Logger)(Level level, const char *msg)
        LOGGER = CFUNCTYPE(None, c_int, c_char_p)

        def logger_message(level, msg):
            """Logger message function for ctypes callback"""
            level = Level(level)
            msg = msg.decode()
            if level in (Level.LEVEL_ALL, Level.LEVEL_DEBUG):
                self.logger.debug(msg)
            elif level == Level.LEVEL_INFO:
                self.logger.info(msg)
            elif level == Level.LEVEL_WARNING:
                self.logger.warning(msg)
            elif level == Level.LEVEL_ERROR:
                self.logger.error(msg)
            elif level == Level.LEVEL_FATAL:
                self.logger.fatal(msg)
            elif level == Level.LEVEL_NONE:
                pass
            else:
                raise ValueError(level)

        # Important: keep this variable alive to prevent DLL crash
        self._callback_function = LOGGER(logger_message)

        # BMI_API void set_logger(Logger callback)
        dll.set_logger.argtypes = [LOGGER]
        dll.set_logger.restype = None
Example #6
0
def __comtype_to_pywin_obj(ptr, interface):
    """Convert a comtypes pointer 'ptr' into a pythoncom PyI<interface> object.

    'interface' specifies the interface we want; it must be a comtypes
    interface class.  The interface must be implemented by the object;
    and the interface must be known to pythoncom.
    """
    com_obj = PyDLL(pythoncom.__file__).PyCom_PyObjectFromIUnknown

    com_obj.restype = ctypes.py_object
    com_obj.argtypes = (ctypes.POINTER(IUnknown), ctypes.c_void_p, BOOL)

    # noinspection PyProtectedMember
    return com_obj(ptr._comobj, byref(interface._iid_), True)
Example #7
0
    def __init__(self, r_home):
        if sys.platform.startswith("win"):
            libR_dir = os.path.join(r_home, "bin",
                                    "x64" if sys.maxsize > 2**32 else "i386")
            libR_path = os.path.join(libR_dir, "R.dll")
        elif sys.platform == "darwin":
            libR_path = os.path.join(r_home, "lib", "libR.dylib")
        elif sys.platform.startswith("linux"):
            libR_path = os.path.join(r_home, "lib", "libR.so")

        if not os.path.exists(libR_path):
            raise RuntimeError("Cannot locate R share library.")

        self.libR = PyDLL(str(libR_path))
        if not hasattr(self.libR, "R_tryCatchError"):
            raise RuntimeError("rtichoke requires R 3.4.0 or above.")
Example #8
0
    def __init__(self):
        if 'R_HOME' not in os.environ:
            Rhome = subprocess.check_output(["R",
                                             "RHOME"]).decode("utf-8").strip()
            os.environ['R_HOME'] = Rhome
        else:
            Rhome = os.environ['R_HOME']
        os.environ["R_DOC_DIR"] = os.path.join(Rhome, "doc")
        os.environ["R_INCLUDE_DIR"] = os.path.join(Rhome, "include")
        os.environ["R_SHARE_DIR"] = os.path.join(Rhome, "share")
        if sys.platform.startswith("win"):
            libR_path = os.path.join(Rhome, "bin",
                                     ['i386',
                                      'x64'][sys.maxsize > 2**32], "R.dll")
        elif sys.platform == "darwin":
            libR_path = os.path.join(Rhome, "lib", "libR.dylib")
        elif sys.platform.startswith("linux"):
            libR_path = os.path.join(Rhome, "lib", "libR.so")

        if not os.path.exists(libR_path):
            raise RuntimeError("Cannot locate R share library.")

        self.libR = PyDLL(str(libR_path))
Example #9
0
    def __init__(self):
        if 'R_HOME' not in os.environ:
            try:
                Rhome = subprocess.check_output(["R", "RHOME"]).decode("utf-8").strip()
            except Exception as e:
                if sys.platform.startswith("win"):
                    Rexe = os.path.join(
                        read_registry("Software\\R-Core\\R", "InstallPath")[0],
                        "bin",
                        "R.exe")
                    Rhome = subprocess.check_output([Rexe, "RHOME"]).decode("utf-8").strip()
                else:
                    raise e

            os.environ['R_HOME'] = Rhome
        else:
            Rhome = os.environ['R_HOME']
        os.environ["R_DOC_DIR"] = os.path.join(Rhome, "doc")
        os.environ["R_INCLUDE_DIR"] = os.path.join(Rhome, "include")
        os.environ["R_SHARE_DIR"] = os.path.join(Rhome, "share")

        if sys.platform.startswith("win"):
            libR_dir = os.path.join(Rhome, "bin", ['i386', 'x64'][sys.maxsize > 2**32])
            os.environ['PATH'] = libR_dir + ";" + os.environ['PATH']

            libR_path = os.path.join(libR_dir, "R.dll")
        elif sys.platform == "darwin":
            libR_path = os.path.join(Rhome, "lib", "libR.dylib")
        elif sys.platform.startswith("linux"):
            libR_path = os.path.join(Rhome, "lib", "libR.so")

        if not os.path.exists(libR_path):
            raise RuntimeError("Cannot locate R share library.")

        self.libR = PyDLL(str(libR_path))
        if not hasattr(self.libR, "R_tryCatchError"):
            raise RuntimeError("rice requires R 3.4.0 or above.")
Example #10
0
from ctypes import PyDLL, py_object, c_int
from sys import exit
from os import path
import numpy as np

my_path = path.abspath(path.dirname(__file__))
path = path.join(my_path, "./bin/libmotion_detector_optimization.so")

try:
    lib = PyDLL(path)
    lib.c_scan.restype = py_object
    lib.c_scan.argtypes = [py_object, c_int]
    lib.c_find_bounding_boxes.restype = py_object
    lib.c_find_bounding_boxes.argtypes = [py_object]
    lib.c_pack.restype = py_object
    lib.c_pack.argtypes = [py_object, py_object]
except OSError:
    print("Error when loading lib")
    exit(1)


def scan(img: np.ndarray, expansion_step: int):
    return lib.c_scan(img, expansion_step)


def optimize_bounding_boxes(rectangles):
    if rectangles is None or not len(rectangles):
        return []
    return lib.c_find_bounding_boxes(rectangles)

Example #11
0
# We use the PyCom_PyObjectFromIUnknown function in pythoncom25.dll to

# convert a comtypes COM pointer into a pythoncom COM pointer.

# Fortunately this function is exported by the dll...

#

# This is the C prototype; we must pass 'True' as third argument:

#

# PyObject *PyCom_PyObjectFromIUnknown(IUnknown *punk, REFIID riid, BOOL bAddRef)

_PyCom_PyObjectFromIUnknown = PyDLL(
    pythoncom.__file__).PyCom_PyObjectFromIUnknown

_PyCom_PyObjectFromIUnknown.restype = py_object

_PyCom_PyObjectFromIUnknown.argtypes = (POINTER(IUnknown), c_void_p, BOOL)


def comtypes2pywin(ptr, interface=None):
    """Convert a comtypes pointer 'ptr' into a pythoncom

    PyI<interface> object.



    'interface' specifies the interface we want; it must be a comtypes
Example #12
0
from __future__ import with_statement

from contextlib import contextmanager, nested
from threading import Thread

from tempfile import mkdtemp
from os.path import join as pjoin
from os import (dup, fdopen, open as osopen, O_NONBLOCK, O_RDONLY, remove,
                rmdir, mkfifo)
from fcntl import fcntl, F_GETFL, F_SETFL
from select import select
from sys import stdout, stderr

from ctypes import PyDLL, CDLL, c_void_p, c_char_p, py_object

pyapi = PyDLL(None)
this_exe = CDLL(None)


def make_fn(what, res, *args):
    what.restype = res
    what.argtypes = args
    return what


FILE_p = c_void_p

PyFile_AsFile = make_fn(pyapi.PyFile_AsFile, FILE_p, py_object)
freopen = make_fn(this_exe.freopen, FILE_p, c_char_p, c_char_p, FILE_p)

Example #13
0
                    visited_files.append((name, repr(os.lstat(name))))
                except:
                    visited_files.append((name, "ERROR calling os.lstat."))

        def strip_name(n):
            if n[:len(main_dir)] == main_dir:
                return "<root>/" + n[len(main_dir):]
            else:
                return n

        print "\n".join(("  %s: %s" % (strip_name(name), stats))
                        for name, stats in sorted(visited_files))

        print "INFO: Loading pylambda worker library: ", pylambda_workers[0]

    pylambda_lib = PyDLL(pylambda_workers[0])

    pylambda_lib.pylambda_worker_main.argtypes = [c_char_p, c_char_p]
    pylambda_lib.pylambda_worker_main.restype = c_int

    if not debug_mode:
        # This call only returns after the parent process is done.
        result = pylambda_lib.pylambda_worker_main(c_char_p(main_dir),
                                                   c_char_p(sys.argv[1]))
    else:
        # This version will print out a bunch of diagnostic information and then exit.
        result = pylambda_lib.pylambda_worker_main(c_char_p(main_dir),
                                                   c_char_p("debug"))

    if debug_mode:
        print "Process exited with code %d." % result
Example #14
0
import os
import sys
import shutil

# Rough way to add to the Python path.
# TODO: find a cleaner way to implement this. You have to switch
# directories currently to find it.
for src in ["ocaml.so", "../_build/default/python/ocaml.so"]:
    if os.path.exists(src):
        shutil.copyfile(src, "mcl/ocaml.so")
sys.path.append(".")

## Enables the shared object file to be understood by Python
from ctypes import PyDLL, RTLD_GLOBAL, c_char_p

curdir = dir_path = os.path.dirname(os.path.realpath(__file__))
dll = PyDLL(f"{curdir}/ocaml.so", RTLD_GLOBAL)
argv_t = c_char_p * 2
argv = argv_t("ocaml.so".encode('utf-8'), None)
dll.caml_startup(argv)

# Import relevant files
from ZXBuilder import ZXBuilder
from CirqBuilder import StrictCirqBuilder, ValidCirqBuilder
Example #15
0
"""Trace code, so that libpymemprofile_api know's where we are."""

import atexit
from ctypes import PyDLL
from datetime import datetime
import os
import sys
import threading
import webbrowser

from ._utils import timestamp_now, library_path
from ._report import render_report

preload = PyDLL(library_path("_filpreload"))
preload.fil_initialize_from_python()


def start_tracing(output_path: str):
    path = os.path.join(output_path, timestamp_now()).encode("utf-8")
    preload.fil_reset(path)
    threading.setprofile(_start_thread_trace)
    preload.register_fil_tracer()


def _start_thread_trace(frame, event, arg):
    """Trace function that can be passed to sys.settrace.

    All this does is register the underlying C trace function, using the
    mechanism described in
    https://github.com/nedbat/coveragepy/blob/master/coverage/ctracer/tracer.c's
    CTracer_call.
Example #16
0
import sys

# The libgraphserver.so object:
lgs = None

# Try loading from the source tree. If that doesn't work, fall back to the installed location.
_dlldirs = [
    os.path.dirname(os.path.abspath(__file__)),
    os.path.dirname(os.path.abspath(__file__)) + '/../../core', '/usr/lib',
    '/usr/local/lib'
]

for _dlldir in _dlldirs:
    _dllpath = os.path.join(_dlldir, 'libgraphserver.so')
    if os.path.exists(_dllpath):
        lgs = PyDLL(_dllpath)
        break

if not lgs:
    raise ImportError(
        "unable to find libgraphserver shared library in the usual locations: %s"
        % "\n".join(_dlldirs))

libc = cdll.LoadLibrary(find_library('c'))


class _EmptyClass(object):
    pass


def instantiate(cls):
Example #17
0
    try:
        import pythoncom
    except ImportError:
        # pywin32 not installed...
        pass
    else:
        # pywin32 is available.  The pythoncom dll contains two handy
        # exported functions that allow to create a VARIANT from a Python
        # object, also a function that unpacks a VARIANT into a Python
        # object.
        #
        # This allows us to create und unpack SAFEARRAY instances
        # contained in VARIANTs, and check for consistency with the
        # comtypes code.

        _dll = PyDLL(pythoncom.__file__)

        # c:/sf/pywin32/com/win32com/src/oleargs.cpp 213
        # PyObject *PyCom_PyObjectFromVariant(const VARIANT *var)
        unpack = _dll.PyCom_PyObjectFromVariant
        unpack.restype = py_object
        unpack.argtypes = POINTER(VARIANT),

        # c:/sf/pywin32/com/win32com/src/oleargs.cpp 54
        # BOOL PyCom_VariantFromPyObject(PyObject *obj, VARIANT *var)
        _pack = _dll.PyCom_VariantFromPyObject
        _pack.argtypes = py_object, POINTER(VARIANT)
        _pack.restype = BOOL

        def pack(obj):
            var = VARIANT()