Objective-C encoding

The Objective-C language has a compiler directive, @encode, that when given a type specification returns a string encoding that type. The type can be a basic type such as an int, a pointer, a tagged structure or union, or a class name – anything, in fact, that can be used as an argument to the C sizeof() operator.

For example:

char *e1 = @encode(int **);
	=> ^^i
char *e2 = @encode(float[12]);
	=> [12f]
char *e3 = @encode(PyStringObject *);
	=> ^{?=i^{_typeobject}il[1c]}

The ObjC module tries to hide as much as possible these details, but nevertheless you may find usefull to understand the mechanism: when you pass a wrong argument to an ObjC message, the exception raised contains the @encoded description of the expected type for that argument, and using the information below you should be able to correctly construct the needed value.

The table below lists the characters used by this mechanism, with their meanings. The third column tells how the particular item type matches with the Python objects. As pointed out above, you can indifferently pass an integer or a string for an argument of type char, but the module translates such values to integers when they are returned by a method.


\begin{tableiii}{\vert c\vert l\vert c\vert}{code}{Code}{Meaning}{Python Equival...
...A pointer to type}{value for type}
\lineiii{?}{An unknown type}{}
\end{tableiii}

The type specification for an array is enclosed within square brackets; the number of elements in the array is specified immediately after the open bracket, before the array type. For example, an array of 12 pointers to floats would be encoded as:

[12^f]

Structures are specified within braces, and unions within parentheses. The structure tag is listed first, followed by an equal sign and the codes for the fields of the structure listed in sequence. For example, this structure,

typedef struct example
{
  id anObject;
  char *aString;
  int anInt;
} Example;

would be encoded like this:

{example=@*i}

The same encoding results whether the defined type name (Example) or the structure tag (example) is passed to @encode(). The encoding for a structure pointer carries the same amount of information about the structure's fields:

^{example=@*i}

However, another level of indirection removes the internal type specification:

^^{example}

Internally, the module uses two functions, pythonify_c_value() and depythonify_c_value() to translate a C value into the corresponding Python object and viceversa. Eventually, in the future, these functions will be moved into an indipendent module, so that they may replace the struct module's functionalities.