How do I expose a C struct to Python using Cython?

Viewed 134

I want to expose the Point C struct to Python. The following code compiles, but the struct is not accessible by Python.

Edit: Point needs to be accessible to other files in the package as well as pure Python code outside the package.

The code

// myfile.h

struct Point {
    double x;
    double y;
};
# blob.pxd

cdef extern from "myfile.h":
    struct Point:
        double x
        double y
# blob.pyx

# empty file
# setup.py

from distutils.core import Extension, setup
from Cython.Build import cythonize

ext = Extension(name="blob", sources=["blob.pyx"])
setup(ext_modules=cythonize(ext,language_level=3))

# call with python setup.py build_ext --inplace

The error

Input 1:

import blob
blob.Point

Output 1:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'blob' has no attribute 'Point'

Input 2:

import blob
blob.__dict__

Output 2:

{
    '__name__': 'blob',
    '__doc__': None,
    '__package__': '',
    '__loader__': <_frozen_importlib_external.ExtensionFileLoader object at 0x000001ADE4F10DC0>,
    '__spec__': ModuleSpec(name='blob', loader=<_frozen_importlib_external.ExtensionFileLoader object at 0x000001ADE4F10DC0>, origin='C:\\Users\\aaron\\Desktop\\project\\cython_with_c\\blob.cp38-win_amd64.pyd'),
    '__file__': 'C:\\Users\\aaron\\Desktop\\project\\cython_with_c\\blob.cp38-win_amd64.pyd',
    '__builtins__': <module 'builtins' (built-in)>, '__test__': {}
}
0 Answers
Related