Skip to content

Instantly share code, notes, and snippets.

@maedoc
Created August 14, 2013 08:24
Show Gist options
  • Save maedoc/6228991 to your computer and use it in GitHub Desktop.
Save maedoc/6228991 to your computer and use it in GitHub Desktop.
"""
Cleaner interaction with class.
Make sure to set the run-time path:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$matlabroot/bin/$arch:$matlabroot/sys/os/$arch
"""
# import the FFI
from ctypes import *
# open the engine library
lib = CDLL('libeng.so')
class MLEng(object):
_buffer, _buffer_size = None, 0
def _set_buffer_size(self, val):
self._buffer_size = val
self._buffer = create_string_buffer(val + 1)
def _get_buffer_size(self):
return self._buffer_size
buffer_size = property(_get_buffer_size, _set_buffer_size)
@property
def output(self):
b = self._buffer
out = b.raw.split(b.raw[-1])[0]
if len(out) == self._buffer_size:
print 'MLEng output buffer filled'
return out
def __init__(self, startcmd="", bufsize=100*1024):
self._eng = lib.engOpen(startcmd)
self.buffer_size = bufsize
lib.engOutputBuffer(self._eng, self._buffer, self.buffer_size)
def __del__(self):
lib.engClose(self._eng)
def __call__(self, cmd, out='print'):
if not type(cmd) in (str,):
cmd = str(cmd)
print '>> ', cmd
lib.engEvalString(self._eng, cmd)
if out == 'print':
print self.output
elif out == 'return':
return self.output
else:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment