[Tutor] Python C extension - which method?
Stefan Behnel
stefan_ml at behnel.de
Sat May 5 17:44:45 EDT 2018
Hi,
Brad M schrieb am 04.05.2018 um 11:30:
> I want to create a C-based memory scanner for Python, and so far this is
> how I do it:
>
> Python:
>
> from ctypes import cdll
> mydll = cdll.LoadLibrary('hello.dll')
> print(mydll.say_something())
>
> and hello.dll:
>
> #include <stdio.h>
> __declspec(dllexport) int say_something()
> {
> return 1980;
> }
>
> so the printout is "1980"
>
> Is this alright?
Depends on your needs and your C/C++ knowledge.
If you have a shared library that provides the ready-made functionality,
and accessing that native code at all is more important than calling it
very quickly (e.g. you only do a few longish-running calls into it), then
wrapping a shared library with ctypes (or preferably cffi) is a good way to
do it.
Otherwise, try either a native wrapper generator like pybind11, or write
your wrapper in Cython.
Specifically, if you are not just calling into an external library 1:1, but
need to do (or can benefit from doing) non-trivial operations in native
code, definitely use Cython.
http://cython.org
> I am aware that there is another much more complicated
> method such as this:
>
> https://tutorialedge.net/python/python-c-extensions-tutorial/#building-and-installing-our-module
Well, yes, it exists, but I advise against wrapping C code manually that
way. It's just too cumbersome and error prone. Leave it to the experts who
have already written their tools for you.
Stefan
Disclosure: I'm a Cython core dev, so I'm biased and I absolutely know what
I'm talking about.
More information about the Tutor
mailing list