import numpy as np from cffi import FFI ffi = FFI() c_data = ffi.new("int[]", [1, 2, 3, 4, 5]) # Create a numpy array that shares memory with the C array np_data = np.frombuffer(ffi.buffer(c_data), np.int32, 5) # Change a value in the Python array and see that it is reflected in the C array np_data[0] = 10 print(c_data[0]) # prints '10'
from cffi import FFI ffi = FFI() ffi.cdef("struct person {char* name; int age;};") c_data = ffi.new("struct person*", {"name": "John", "age": 30}) # Create a Python dictionary that shares memory with the C struct py_data = ffi.from_buffer("struct person", c_data) # Change a value in the Python dictionary and see that it is reflected in the C struct py_data["name"] = "Jane" print(c_data.name.decode()) # prints 'Jane'This example creates a C struct representing a person and then creates a Python dictionary that shares memory with the C struct. Any changes made to the Python dictionary will be reflected in the C struct. Package library used: None, only core packages used in the example.