Friday, June 29, 2012

python, numpy, c and ctypes

so, it is very easy for combining c and python together. 
and it is also very confusing because there are alot of ways to do such same task

for instance, there are boost, swig, sip and shiboken
i think it would better to standarize the interface and integrate it into new python 3000
anyway, here are some collections of how to do such 

1. memory address -> numpy array: 

ctypes_array = (ctypes.c_char * MEM_SIZE).from_address(pointer) 
numpy_array = numpy.frombuffer(ctypes_array, dtype=numpy.float64)
numpy_array

2. numpy array -> memory address
pointer = ndarray.__array_interface__['data'][0]

3. numpy array -> ctype pointer, which is already wrapped, not a simple address 

data = numpy.array([[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]])
data = data.astype(numpy.float32)
c_float_p = ctypes.POINTER(ctypes.c_float)
data_p = data.ctypes.data_as(c_float_p)
then if we want to access the data at this address, use the function contents()

actually all these can be done in a standard numpy way, pls refer to :
C-Types Foreign Function Interface (numpy.ctypeslib)

Sunday, June 17, 2012

python tricks

1.      String to dict
eval(string)
or
import ast
ast.literal_eval(string)

the later one is considered to be safer

2.      The config parser module use cap letter for section name, and uncap for options , no matter what is the input.



Tuesday, June 12, 2012

Python packaging and installation

in setup.py file
for instance ::
    from distutils.core import setup
    setup(
      name = 'MyTools',
      version = '0.1.0',
      author = 'zhijia yuan',
      packages = ['oct'],
      author_email = 'zyuan@topcon.com',
      install_requires = ['NumPy >= 1.0.4'],
      )

after installation, the available import is related to the packages name::
    import oct #works
    import MyTools.oct #doesnot work
which means that the name MyTools just a top tag for your package, and oct is the real package name that you can import
if you have multiple packages, it would be more reasonable to keep the name and package name organized.