python-cffi-example | simple example Python CFFI package
kandi X-RAY | python-cffi-example Summary
kandi X-RAY | python-cffi-example Summary
A simple example Python + CFFI package (including testing, development, and packaging)
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
- Determine if pattern matches pattern
- Convert to bytes
python-cffi-example Key Features
python-cffi-example Examples and Code Snippets
Community Discussions
Trending Discussions on python-cffi-example
QUESTION
I was trying to follow this example to attempt to create a simple hash table in C that I could use in Python (using CFFI). Following are the corresponding files and relevant code.
hash_table.h
:
ANSWER
Answered 2020-Jul-05 at 18:45See https://cffi.readthedocs.io/en/latest/using.html#extern-python-and-void-arguments. Avoid using PyObject *
with CFFI. The correct answer is to keep int cmp_function(const void*, const void*);
. I will assume that you already use ffi.new_handle()
to convert the objects to the void *
equivalent that you can send to C (in the add_to_hash_table()
method, etc.) and ffi.from_handle()
to read them back (in the get_from_hash_table()
method, etc.).
To implement the comparison function, you declare a function in Python with extern "Python"
, as in the above document. Then you use that function for the cmp_function
pointer in your struct. Inside that Python function, you receive the two arguments as two void *
. You first convert them back to the original Python objects with ffi.from_handle()
, and then just use regular Python---in your case, probably just if x == y: return 1; else: return 0
or similar.
Be careful about keeping the Python objects alive after calling ffi.new_handle()
. They are not kept alive just by the fact that their void *
representation happens to be stored inside some C structures.
Note that CFFI is not quite well suited to implement pure data structures, because all these conversions and multiple storages that increase the overhead when compared with the direct CPython-C-API approach.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install python-cffi-example
You can use python-cffi-example like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page