Search code examples
pythoncapictypesspeex

Python ctypes & libspeex.dll/libspeex.so; what are the equivilents to #define, typedef, and structs?


I have a reference of the dll file here: http://speex.org/docs/api/speex-api-reference/group__Codec.html

What I'm wondering is, in that list, there are a lot of defines. What is the python equivalent, same for the struct class, what are my options for implementing all of this with ctypes? Typedefs?

I'm relatively inexperienced with python so please pardon me if I'm less than adequate in my skill. No colleges teach it around here so I'm trying to learn via asking & google.

Right now I'm just trying to basically figure out how to interface with this speex library so I can at least start using the encode/decode functions. But I am unsure of implementation of those 3 things. I'm sure I'm over my head with this but in the end it seems I always come out on top learning something new. Anyone mind giving me a brief rundown?

From what I take it #define in all practical purposes is basically just foo = bar?
And Class:Struct SpeexMode would be a class, that has all of the listed functions?

Or is all of this already defined in the compiled DLL? If so, I've already done a small dll file call with ctypes via a tutorial I ran across. Would it be as simple as setting up the environment (passing these variables into the functions to set things such as codec quality, invoking the encoder, then using the encoder?)


Solution

  • To use structs, you indeed should declare them with ctypes.Structure to let Python know about them.

    >>> from ctypes import *
    >>> class POINT(Structure):
    ...     _fields_ = [("x", c_int),
    ...                 ("y", c_int)]
    ...
    >>> point = POINT(10, 20)
    >>> print point.x, point.y
    10 20
    >>> point = POINT(y=5)
    >>> print point.x, point.y
    0 5
    >>> POINT(1, 2, 3)
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    ValueError: too many initializers
    >>>
    

    As for defines, they're part of the include file usually, so you'll just have to define them yourself in the Python code, because the C compiler doesn't even see them (defines are converted to their values by the pre-processor).

    If you're looking for a more automatic converter from C/C++ interfaces to Python, look at SWIG. SWIG, unlike ctypes, requires you to use a C compiler in addition to pure Python.