def set_home_parameter(self, home_dir, switch_dir, home_vel, zero_offset):
""" Set the home parameters.
@param int home_dir: direction to the home position,
1 = Move forward
2 = Move backward
@param int switch_dir: Direction of the switch limit:
4 = Use forward limit switch for home datum
1 = Use forward limit switch for home datum.
@param float home_vel = default velocity
@param float zero_offset: the distance or offset (in mm or degrees) of
the limit switch from the Home position.
"""
home_dir_c = c_long(home_dir)
switch_dir_c = c_long(switch_dir)
home_vel_c = c_float(home_vel)
zero_offset_c = c_float(zero_offset)
self.aptdll.MOT_SetHomeParams(self.SerialNum, home_dir_c, switch_dir_c,
home_vel_c, zero_offset_c)
return True
python类c_long()的实例源码
def get_status(self):
""" Get the status bits of the current axis.
@return tuple(int, dict): the current status as an integer and the
dictionary explaining the current status.
"""
status_bits = c_long()
self.aptdll.MOT_GetStatusBits(self.SerialNum, pointer(status_bits))
# Check at least whether magnet is moving:
if self._test_bit(status_bits.value, 4):
return 1, self._create_status_dict()
elif self._test_bit(status_bits.value, 5):
return 2, self._create_status_dict()
else:
return 0, self._create_status_dict()
def _coord_byval(coord):
"""
Turns a COORD object into a c_long.
This will cause it to be passed by value instead of by reference. (That is what I think at least.)
When runing ``ptipython`` is run (only with IPython), we often got the following error::
Error in 'SetConsoleCursorPosition'.
ArgumentError("argument 2: <class 'TypeError'>: wrong type",)
argument 2: <class 'TypeError'>: wrong type
It was solved by turning ``COORD`` parameters into a ``c_long`` like this.
More info: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx
"""
return c_long(coord.Y * 0x10000 | coord.X & 0xFFFF)
#: If True: write the output of the renderer also to the following file. This
#: is very useful for debugging. (e.g.: to see that we don't write more bytes
#: than required.)
def test_int_pointers(self):
from ctypes import c_short, c_uint, c_int, c_long, POINTER, pointer
LPINT = POINTER(c_int)
## p = pointer(c_int(42))
## x = LPINT.from_param(p)
x = LPINT.from_param(pointer(c_int(42)))
self.assertEqual(x.contents.value, 42)
self.assertEqual(LPINT(c_int(42)).contents.value, 42)
self.assertEqual(LPINT.from_param(None), None)
if c_int != c_long:
self.assertRaises(TypeError, LPINT.from_param, pointer(c_long(42)))
self.assertRaises(TypeError, LPINT.from_param, pointer(c_uint(42)))
self.assertRaises(TypeError, LPINT.from_param, pointer(c_short(42)))
def test_int_pointers(self):
from ctypes import c_short, c_uint, c_int, c_long, POINTER, pointer
LPINT = POINTER(c_int)
## p = pointer(c_int(42))
## x = LPINT.from_param(p)
x = LPINT.from_param(pointer(c_int(42)))
self.assertEqual(x.contents.value, 42)
self.assertEqual(LPINT(c_int(42)).contents.value, 42)
self.assertEqual(LPINT.from_param(None), None)
if c_int != c_long:
self.assertRaises(TypeError, LPINT.from_param, pointer(c_long(42)))
self.assertRaises(TypeError, LPINT.from_param, pointer(c_uint(42)))
self.assertRaises(TypeError, LPINT.from_param, pointer(c_short(42)))
def test_array_pointers(self):
from ctypes import c_short, c_uint, c_int, c_long, POINTER
INTARRAY = c_int * 3
ia = INTARRAY()
self.assertEqual(len(ia), 3)
self.assertEqual([ia[i] for i in range(3)], [0, 0, 0])
# Pointers are only compatible with arrays containing items of
# the same type!
LPINT = POINTER(c_int)
LPINT.from_param((c_int*3)())
self.assertRaises(TypeError, LPINT.from_param, c_short*3)
self.assertRaises(TypeError, LPINT.from_param, c_long*3)
self.assertRaises(TypeError, LPINT.from_param, c_uint*3)
## def test_performance(self):
## check_perf()
def CellQuality(grid):
"""
Given a vtk unstructured grid, returns the minimum scaled jacobian cell
quality for each cell. Unstructured grid can only contain the following
elements
tetrahedral
pyramid
wedge
hexahedral
Elements may be linear or quadradic
"""
# Get cells and points from grid
cells = grid.GetNumpyCells(ctypes.c_long)
points = grid.GetNumpyPoints(ctypes.c_double)
return _cellqual.CompScJac_quad(cells, points)
def CoCreateInstanceC2R (self, store, reg, clsid, iid) :
# Ugly code to find DLL in C2R version of COM object and get a COM
# object despite the fact that COM doesn't handle C2R
try:
# Get DLL to load from 2R register
aReg = winreg.ConnectRegistry(None, store)
aKey = winreg.OpenKey(aReg, reg, 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
dummy_n, IconvDLL, dummy_t = winreg.EnumValue(aKey, 0)
winreg.CloseKey(aKey)
winreg.CloseKey(aReg)
# Create OLE object from DLL
IconvOLE = ctypes.OleDLL(IconvDLL)
# Get COM Instance from OLE
clsid_class = uuid.UUID(str(clsid)).bytes_le
iclassfactory = uuid.UUID(str(pythoncom.IID_IClassFactory)).bytes_le
com_classfactory = ctypes.c_long(0)
IconvOLE.DllGetClassObject(clsid_class, iclassfactory, ctypes.byref(com_classfactory))
MyFactory = pythoncom.ObjectFromAddress(com_classfactory.value, pythoncom.IID_IClassFactory)
return MyFactory.CreateInstance (None, str(iid))
except:
return None
def terminate_thread(thread):
"""Terminate a python thread from another thread.
:param thread: a threading.Thread instance
"""
if not thread.isAlive():
return
# print('valet watcher thread: notifier thread is alive... - kill it...')
exc = ctypes.py_object(SystemExit)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread.ident), exc)
if res == 0:
raise ValueError("nonexistent thread id")
elif res > 1:
# If it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
# print('valet watcher thread exits')
def _async_raise(tid, exctype):
'''Raises an exception in the threads with id tid'''
if not inspect.isclass(exctype):
raise TypeError("Only types can be raised (not instances)")
try:
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))
except AttributeError:
# To catch: undefined symbol: PyThreadState_SetAsyncExc
return
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# "if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), 0)
raise SystemError("PyThreadState_SetAsyncExc failed")
def _set(self, dropout, seed):
if self.state is None and dropout > 0:
dropout_states_size = ctypes.c_long()
check_error(lib.cudnnDropoutGetStatesSize(
self.handle,
ctypes.byref(dropout_states_size)))
self.state = torch.cuda.ByteTensor(dropout_states_size.value)
state_ptr = self.state.data_ptr()
state_size = self.state.size(0)
else:
state_ptr = None
state_size = 0
check_error(lib.cudnnSetDropoutDescriptor(
self,
self.handle,
ctypes.c_float(dropout),
ctypes.c_void_p(state_ptr),
ctypes.c_size_t(state_size),
ctypes.c_ulonglong(seed),
))
self.dropout = dropout
def test_int_pointers(self):
from ctypes import c_short, c_uint, c_int, c_long, POINTER, pointer
LPINT = POINTER(c_int)
## p = pointer(c_int(42))
## x = LPINT.from_param(p)
x = LPINT.from_param(pointer(c_int(42)))
self.assertEqual(x.contents.value, 42)
self.assertEqual(LPINT(c_int(42)).contents.value, 42)
self.assertEqual(LPINT.from_param(None), None)
if c_int != c_long:
self.assertRaises(TypeError, LPINT.from_param, pointer(c_long(42)))
self.assertRaises(TypeError, LPINT.from_param, pointer(c_uint(42)))
self.assertRaises(TypeError, LPINT.from_param, pointer(c_short(42)))
def _coord_byval(coord):
"""
Turns a COORD object into a c_long.
This will cause it to be passed by value instead of by reference. (That is what I think at least.)
When runing ``ptipython`` is run (only with IPython), we often got the following error::
Error in 'SetConsoleCursorPosition'.
ArgumentError("argument 2: <class 'TypeError'>: wrong type",)
argument 2: <class 'TypeError'>: wrong type
It was solved by turning ``COORD`` parameters into a ``c_long`` like this.
More info: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx
"""
return c_long(coord.Y * 0x10000 | coord.X & 0xFFFF)
#: If True: write the output of the renderer also to the following file. This
#: is very useful for debugging. (e.g.: to see that we don't write more bytes
#: than required.)
def ENrunH(self):
"""
solves hydraulics for conditions at time t.
Returns: long
* current simulation time (seconds)
This function is used in a loop with ENnextH() to run
an extended period hydraulic simulation.
See ENsolveH() for an example.
"""
lT = ctypes.c_long()
self.errcode = self.ENlib.ENrunH(byref(lT))
self._error()
self.cur_time = lT.value
return lT.value
def ENnextH(self):
"""
determines time until next hydraulic event.
Returns:
* time (seconds) until next hydraulic event
(0 marks end of simulation period)
This function is used in a loop with ENrunH() to run
an extended period hydraulic simulation.
See ENsolveH() for an example.
"""
lTstep = ctypes.c_long()
self.errcode = self.ENlib.ENnextH(byref(lTstep))
self._error()
return lTstep.value
def ENrunQ(self):
"""
retrieves hydraulic & WQ results at time t.
Returns: long
* current simulation time (seconds)
This function is used in a loop with ENnextQ() to run
an extended period WQ simulation. See ENsolveQ() for
an example.
"""
lT = ctypes.c_long()
self.errcode = self.ENlib.ENrunQ(byref(lT))
self._error()
return lT.value
def ENnextQ(self):
"""
advances WQ simulation to next hydraulic event.
Returns: long
* time (seconds) until next hydraulic event
(0 marks end of simulation period)
This function is used in a loop with ENrunQ() to run
an extended period WQ simulation. See ENsolveQ() for
an example.
"""
lTstep = ctypes.c_long()
self.errcode = self.ENlib.ENnextQ(byref(lTstep))
self._error()
return lTstep.value
def _coord_byval(coord):
"""
Turns a COORD object into a c_long.
This will cause it to be passed by value instead of by reference. (That is what I think at least.)
When runing ``ptipython`` is run (only with IPython), we often got the following error::
Error in 'SetConsoleCursorPosition'.
ArgumentError("argument 2: <class 'TypeError'>: wrong type",)
argument 2: <class 'TypeError'>: wrong type
It was solved by turning ``COORD`` parameters into a ``c_long`` like this.
More info: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx
"""
return c_long(coord.Y * 0x10000 | coord.X & 0xFFFF)
#: If True: write the output of the renderer also to the following file. This
#: is very useful for debugging. (e.g.: to see that we don't write more bytes
#: than required.)
def list_alttab_windows(cls):
"""
Return the list of the windows handles that are currently guessed to be
eligible to the Alt+Tab panel.
Raises a OSError exception on error.
"""
# LPARAM is defined as LONG_PTR (signed type)
if ctypes.sizeof(ctypes.c_long) == ctypes.sizeof(ctypes.c_void_p):
LPARAM = ctypes.c_long
elif ctypes.sizeof(ctypes.c_longlong) == ctypes.sizeof(ctypes.c_void_p):
LPARAM = ctypes.c_longlong
EnumWindowsProc = ctypes.WINFUNCTYPE(
ctypes.c_bool, ctypes.c_void_p, LPARAM)
def _enum_proc(hwnd, lparam):
try:
if cls.is_alttab_window(hwnd):
handles.append(hwnd)
except OSError:
pass
return True
handles = []
ctypes.windll.user32.EnumWindows(EnumWindowsProc(_enum_proc), 0)
return handles
def ptrace(command, pid=0, arg1=0, arg2=0, check_errno=False):
if HAS_CPTRACE:
try:
set_errno(0)
result = _ptrace(command, pid, arg1, arg2, check_errno)
except ValueError as errobj:
message = str(errobj)
errno = get_errno()
raise PtraceError(message, errno=errno, pid=pid)
else:
result = _ptrace(command, pid, arg1, arg2)
result_signed = c_long(result).value
if result_signed == -1:
errno = get_errno()
# peek operations may returns -1 with errno=0:
# it's not an error. For other operations, -1
# is always an error
if not(check_errno) or errno:
message = "ptrace(cmd=%s, pid=%s, %r, %r) error #%s: %s" % (
command, pid, arg1, arg2,
errno, strerror(errno))
raise PtraceError(message, errno=errno, pid=pid)
return result