# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
from ctypes import *
from numpy import *

# define native structs
class Data1(Structure):
    _fields_ = [('iv', c_int), ('sv', c_char * 50)]

class Data2(Structure):
    _fields_ = [('iv1', c_int), ('sv1', c_char * 50), ('iv2', c_int), ('sv2', c_char * 50)]

# load library
cdll.LoadLibrary('stddemolib.dll')

# define function prototypes
demolib = cdll.stddemolib
demolib.std_add.argtypes = [c_int, c_int]
demolib.std_add.restype = c_int
demolib.std_sum.argtypes = [c_int, ctypeslib.ndpointer(dtype=int32)]
demolib.std_sum.restype = c_int
demolib.std_dup.argtypes = [c_char_p]
demolib.std_dup.restype = c_char_p
demolib.std_get_out.argtypes = [POINTER(c_int), POINTER(c_char_p)]
demolib.std_get_out.restype = None
demolib.std_get_ret.argtypes = []
demolib.std_get_ret.restype = POINTER(Data1)
demolib.std_chg.argtypes = [POINTER(Data2)]
demolib.std_chg.restype = None

# handling data types:
#     in int as is
#     out int wrap with byref function and use value
#     return int as is
#     in int array wrap with array function
#     in string wrap with str function and encode to byte array
#     out string wrap with byref function, use value and decode from byte array
#     return string decode from byte array
#     inout struct wrap with byref function
#     return struct use contents
def add(a, b):
    return demolib.std_add(a, b)

def sum(a):
    return demolib.std_sum(len(a), array(a))

def dup(s):
    return demolib.std_dup(str(s).encode('UTF-8')).decode('UTF-8')

def get_out(): 
    iv = c_int()
    sv = c_char_p()
    demolib.std_get_out(byref(iv), byref(sv))
    return (iv.value, sv.value.decode('UTF-8'))

def get_ret():
    d = demolib.std_get_ret()
    return (d.contents.iv, d.contents.sv.decode('UTF-8'))

def chg(d):
    nd = Data2();
    nd.iv1 = d.iv1
    nd.sv1 = str(d.sv1).encode('UTF-8')
    demolib.std_chg(byref(nd))
    d.iv2 = nd.iv2
    d.sv2 = nd.sv2.decode('UTF-8')
    return d
