Commit 23bc5efd212b0d2f22eab1ea00434439bccee9f7
1 parent
da1dd36e
Add comments and helper func docstrings for future reference
Showing
1 changed file
with
36 additions
and
7 deletions
scripts/brpy/__init__.py
| 1 | 1 | from ctypes import * |
| 2 | 2 | import os |
| 3 | 3 | |
| 4 | +# some notes on ctypes: | |
| 5 | +# first, you have to make an object that talks directly to the compiled C object | |
| 6 | +# then, for each function in the C API, the user must define the input/return types | |
| 7 | +# not setting the argtypes means no args, not setting restypes is void | |
| 8 | +# there are the normal types, like c_int, c_bool, c_float, c_int_p (char*) | |
| 9 | +# for char** and *char[], we use POINTER(c_char_p) | |
| 10 | +# and c_void_p for void* | |
| 11 | + | |
| 12 | +# these helper functions are just for code reuse - | |
| 13 | +# they generate common arguments for the C API functions | |
| 14 | + | |
| 4 | 15 | def _string_args(n): |
| 5 | - s = [] | |
| 6 | - for i in range(n): | |
| 7 | - s.append(c_char_p) | |
| 8 | - return s | |
| 16 | + ''' | |
| 17 | + Returns n char* | |
| 18 | + ''' | |
| 19 | + s = [] | |
| 20 | + for i in range(n): | |
| 21 | + s.append(c_char_p) | |
| 22 | + return s | |
| 9 | 23 | |
| 10 | 24 | def _var_string_args(n): |
| 11 | - s = [c_int, POINTER(c_char_p)] | |
| 12 | - s.extend(_string_args(n)) | |
| 13 | - return s | |
| 25 | + ''' | |
| 26 | + Returns one int and one char** followed by n char* | |
| 27 | + ''' | |
| 28 | + s = [c_int, POINTER(c_char_p)] | |
| 29 | + s.extend(_string_args(n)) | |
| 30 | + return s | |
| 14 | 31 | |
| 15 | 32 | def _handle_string_func(func): |
| 33 | + ''' | |
| 34 | + A helper function to make the C functions | |
| 35 | + that populate string buffers more pythonic. | |
| 36 | + The functions in the C API return an int | |
| 37 | + (the length of the returned string buffer) | |
| 38 | + and put the return value in a string buffer. | |
| 39 | + This function replaces the call to the C obj with two calls - | |
| 40 | + a) one with empty string to get length | |
| 41 | + b) one with a string of that length to get the actual value | |
| 42 | + Then it returns the string itself. This way, the user of brpy | |
| 43 | + doesn't need to do this stupid magic for themselves. Hooray! | |
| 44 | + ''' | |
| 16 | 45 | def call_func(*args): |
| 17 | 46 | howlong = func('', 0, *args) |
| 18 | 47 | msg = 'x'*(howlong-1) | ... | ... |