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.

2
  • 1
    Do the functions have to actually exist? You could simply create a dynamic wrapper based on the funcs dict. See stackoverflow.com/questions/17734618/… for an example. Commented Feb 18, 2015 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. Commented Feb 18, 2015 at 12:08

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks , this worked. I had to use setattr instead of globals as it the functions had to be added to a class.
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.

1 Comment

this is something i can use . But just now i found something called cog , it might be possible to use that python.org/about/success/cog

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.