Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have an internal API, written in C, which I'd like to write a Python wrapper around it. The API is well structured: it has a few data structs and functions for each kind of struct, like this:

struct XYZ;

MYAPI_XyzDoBuzz(XYZ* xyz, int other, int parameters);
MYAPI_XyzDoFizz(XYZ* xyz, int other, double funky, int parameters);

I was thinking into creating a myapi module and a class Xyz inside this module with methods like do_buzz and do_fizz. Each method would call it's corresponding function in the dynamic library, probably through ctypes (maybe the module keeping a global variable with the result from the ctypes.CDLL call).

Is my proposed structure a good way to expose this API to Python? Are there guidelines and best practices examples for wrapping C dlls for Python?

share|improve this question
The Python library already installed on your machine has numerous examples of this. You could start with math and time as examples. os is another one to read. – S.Lott Jul 6 '11 at 20:49

2 Answers

Have you tried using swig to generate your wrapper? The projects page will give you many examples of swig in action to see what sort of code it produces.

share|improve this answer

The original doc on extending Python might be worth a look. It's a bit old-school with a lot of details to track, but if you take the time to plod through it, you'll understand things thoroughly. Mapping structs to Python objects works as you described it, and is covered in detail in section 2.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.