ctypes
made easy
Peter Edwards, Arista Networks.
peadar@arista.com
Repeats what's in the C source, with different syntax.
Can we get the compiler to output something for us?
Actually, it already does
objdump
--dwarf=info libbasic.so >
basic-objdump.out
We can use this:
To generate this:
Now, how does our boilerplate look?
As well as
reducing the size of the code, changes in
the C code are automatically updated in
the generated python, so if we change the
return value of our function, to, say,
double
, there are no nasty
surprises.
As we use more types, the savings increase. We've removed thousands of lines of hand-written boilerplate.
extern void entry(int expect_return, int expect_i); // this is what we want to test...
extern int f(int ival, const char *sval, int * ipval); // ... but it calls this
Easy!
@CMock.Mock(lib.f, lib)
def mockedF(i, s, iptr):
iptr[0] = 101
return 100
entry
is
called, instead of calling the f
function from the C program, it calls our python
function, mockedF
ctypes
allows us to pass python "callbacks"
to C functions, just like we can pass
int
s and double
s -
it creates a C callable pointer-to-function
from your python function.
Lots of people helped with this, with code, suggestions, testing, and helping make it open source.
Denis Evoy reviewed lots of my bad decisions, and made me fix them. He, Joanne Mikkellson, Sharad Birmiwal, Asang Dani, and Josh Pfosi all made lots of suggestions and found lots of bugs that made it better.
Pawel Kurdybacha helped me prepare the source for github.
Thanks to Arista for being the kind of place that lets me do cool things like this, and then share them with the rest of the world
The ctypes module in python: https://docs.python.org/3/library/ctypes.html
CTypegen package (coming soon): https://github.com/aristanetworks/ctypegen
Presentation slides https://aristanetwork.github.io/ctypegen
(Slides were done with reveal.js, and Cal Evans's extern.hs)