Hacker News new | ask | show | jobs
by joss82 999 days ago
`ctypes` is part of Python's standard library and allows you to directly call C functions from Python code.

It's glorious in its simplicity.

https://docs.python.org/3/library/ctypes.html

2 comments

"Glorious" and "simplicity" are definitely words I've never read about ctypes before.

"Wonky" and "terrifying", a lot more. ctypes is... useful, but it also uses somewhat strange terminology which can be hard to match to C's as it's trying to bridge C and Python. And when getting it wrong is an UB, it's pretty frustrating.

It also doesn't help you use numpy arrays with C functions, which is one of the big selling points of cython.
You can absolutely use numpy arrays with C functions using ctypes. Numpy has `numpy.ctypeslib` which takes care of some of the boilerplate involved.
Yes, you can, but it is easier in cython, and that is one of the key selling points of cython.

Nothing wrong with using ctypes. It's the right solution for some things. However, cython is generally easier with numpy than numpy.ctypeslib

I think ctypes shines when it comes to fast prototyping, since you can iterate on the python bindings without a compilation step. It can also simplify distribution since the bindings can be pure python. Where it's arguably not so good is performance and maintainability.
Yeah, I'd agree with that. Ctypes does have advantages for several use cases, and quick iteration is one of those, for sure.

It's definitely a good tool to have in your toolbox!