#

Cython FAQ

## Contents

- How do I call Python/C API routines?
- How do I convert a C string containing null bytes to a Python string?
- How do I access the data inside a Numeric array object?
- Cython says my extension type object has no attribute 'rhubarb', but I know it does. What gives?
- Python says my extension type has no method called 'quack', but I know it does. What gives?

## How do I call Python/C API routines?

Declare them as C functions inside a `cdef extern from` block. Use the type name `object` for any parameters and return types which are Python object references. Don't use the word `const` anywhere. Here is an example which defines and uses the `PyString_FromStringAndSize` routine:

> `cdef extern from "Python.h":`
> `object PyString_FromStringAndSize(char *, int)`

> `cdef char buf[42]`
> `my_string = PyString_FromStringAndSize(buf, 42)`

## How do I convert a C string containing null bytes to a Python string?

Put in a declaration for the `PyString_FromStringAndSize` API routine and use that`.` See How do I call Python/C API routines?

## How do I access the data inside a Numeric array object?

Use a `cdef extern from` block to include the Numeric header file and declare the array object as an external extension type. The following code illustrates how to do this:

> `cdef extern from "Numeric/arrayobject.h":`

> `struct PyArray_Descr:`
> `int type_num, elsize`
> `char type`

> `ctypedef class Numeric.ArrayType [object PyArrayObject]``:`
> `cdef char *data`
> `cdef int nd`
> `cdef int *dimensions, *strides`
> `cdef object base`
> `cdef PyArray_Descr *descr`
> `cdef int flags
> `

For more information about external extension types, see the "External Extension Types" section of the "Extension Types" documentation page.
``

## Cython says my extension type object has no attribute 'rhubarb', but I know it does. What gives?

You're probably trying to access it through a reference which Cython thinks is a generic Python object. You need to tell Cython that it's a reference to your extension type by means of a declaration,
for example,

> `cdef class Vegetables:`
> `cdef int rhubarb`
> `...`
> `cdef Vegetables veg`
> `veg.rhubarb = 42`

Also see the "Attributes" section of the "Extension Types" documentation page.

## Python says my extension type has no method called 'quack', but I know it does. What gives?

You may have declared the method using cdef instead of def. Only functions and methods declared with def are callable from Python code.
---