Friday, July 15, 2011

Prepping a library for Python

I've been reading a bit about the CTypes module in Python and I want to see if I can call a library I wrote to do something interesting, like read something out of a binary file - something I can set up pretty quickly in C now but wouldn't know where to start in Python. So, it follows I should write a library for that purpose in C and call it from Python. I'm almost done with it - here's the meat of it:



I'm writing two versions of a function that gets an array of long integers out of the file. One version of the function returns a pointer to an allocated array that contains all the data. The other version of the function (TBD) requires this allocation be done before-hand and you pass it the address of the array for it to fill. I did this because I'm not sure which is the most appropriate way to do things in Python. Hopefully both will work and that will give me a really good feel for that module and make fleshing out the library much easier.

I went a bit overboard compartmentalizing functions. The "skip" functions could have been one function but I went for verbosity over brevity.

An early draft of the function for getting data involved an elaborate flagging system where you passed NULL as the array to be filled and an address of an integer if you wanted to just get the number of data to be returned, and the opposite (address of array to fill and NULL of integer address) to get the data out. This I decided was too complicated AND I realized that the capability to overload function names (use the same function name in different contexts depending on how you call it) in C++ would have been useful.

I banged this out in two evenings but to be honest I did recycle some code from prior similar projects (maybe a dozen lines total recycled). This weekend is going to be nutty but I hope to have this code in a static library next week for some Python testing. Right now it's just a .c file in a vanilla console program project in XCode and in main.c I have some quick verification tests where I ask for data I know the values of.

Onwards and onwards.

EDIT: This project has certainly been a big retesting of my pointer knowledge - especially since I do more allocating here than I've ever done. FYI the function that returns a pointer to an allocated array assumes that you free it later.

No comments:

Post a Comment