2

I need to call functions in a C dll from python. So I need to write functions of the format

def funcA(self):
    ans = ctypes.uint64()
    self.driver.getA(ctypes.byref(ans))
    return ans

now I have to write the same code about 30 times, the only difference in each being the name of function called funcA , funcB , funcC and similarly the dll function getA, getB, getC and the type of the return values which can vary

typically I could like to just have a dict

funcs = { 'A':'uint64', 'B':'bool'}

and automatically generate functins

funcA and funcB , with almost the same structure as shown on top , except for the types and the variable names. I would guess there would be some libraries for it.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
Abhijit Ray
  • 105
  • 1
  • 6
  • 1
    Do the functions have to actually exist? You could simply create a dynamic wrapper based on the `funcs` dict. See https://stackoverflow.com/questions/17734618/dynamic-method-call-in-python-2-7-using-strings-of-method-names for an example. – Mark R. Feb 18 '15 at 12:04
  • I would prefer to have the functions exist , as the final output will be a python library which interfaces with the c dll ( the idea is to keep the function names the same as it is in the C dll ), the user of the library should not have to use the funcs dict. – Abhijit Ray Feb 18 '15 at 12:08

2 Answers2

3

Why use strings rather than the types themselves?

funcs = { 'A':ctypes.uint64, 'B':bool }

Then:

def make_func(name, ctype):
    def func(self):
        ans = ctype()
        getattr(self.driver, 'get'+name)(ctypes.byref(ans))
        return ans
   func.__name__ = 'func'+name
   return func

for a, b in funcs.items():
    globals()['func'+a] = make_func(a, b)

Or ditch the dict and for loop and:

funcA = make_func('A', ctypes.uint64)
funcB = make_func('B', bool)
Duncan
  • 92,073
  • 11
  • 122
  • 156
2

If you want to do this with code generation, you could just create some template for the function and then use str.format to fill in the parameters from your dictionary.

template = """def func{0}(self):
    ans = ctypes.{1}()
    self.driver.get{0}(ctypes.byref(ans))
    return ans
    """

funcs = { 'A':'uint64', 'B':'bool'}

for a, b in funcs.items():
    function = template.format(a, b)
    print function

Just pipe the output to some file, or directly write it to a file instead of printing.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • this is something i can use . But just now i found something called cog , it might be possible to use that https://www.python.org/about/success/cog/ – Abhijit Ray Feb 18 '15 at 12:12