43 lines
1.4 KiB
Python
43 lines
1.4 KiB
Python
import ctypes
|
|
hello_lib = ctypes.CDLL('./hello.so') #/windows
|
|
|
|
# 1. Square (int -> int)
|
|
hello_lib.square.argtypes = [ctypes.c_int]
|
|
hello_lib.square.restype = ctypes.c_int
|
|
|
|
x = 4
|
|
result = hello_lib.square(x)
|
|
print(f'the square of {x} is {result}')
|
|
|
|
hello_lib.sum_elements.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_int]
|
|
hello_lib.sum_elements.restype = ctypes.c_int
|
|
|
|
# 2. Sum (int*, int -> int)
|
|
N = 4
|
|
p = [3, 1, 2, 4]
|
|
# Converts Python list to C array. (*p) is equivalent to (3, 1, 2, 4)
|
|
c_array = (ctypes.c_int * len(p))(*p)
|
|
# Get the address of the array
|
|
p_pointer = ctypes.cast(c_array, ctypes.POINTER(ctypes.c_int))
|
|
|
|
result = hello_lib.sum_elements(p_pointer, N) # pass in p_pointer or c_array both works
|
|
print(f"the sum of the array is {result}")
|
|
|
|
import numpy as np
|
|
from numpy.ctypeslib import ndpointer
|
|
|
|
# 3. Sort (in place float*)
|
|
hello_lib.bubble_sort.argtypes = [ndpointer(dtype=np.float32, flags='C_CONTIGUOUS'), ctypes.c_int]
|
|
hello_lib.bubble_sort.restype = None
|
|
arr = np.array([3.0, 2.3, 4.2, 1.9, 3.2, 1.7], dtype=np.float32)
|
|
hello_lib.bubble_sort(arr, len(arr))
|
|
print(arr)
|
|
|
|
# 4. Create (int, float -> float*)
|
|
a = 0.523
|
|
N = 6
|
|
hello_lib.generate_sine_values.argtypes = [ctypes.c_float, ctypes.c_int]
|
|
hello_lib.generate_sine_values.restype = ndpointer(dtype=np.float32, shape=(N,))
|
|
result_arr = hello_lib.generate_sine_values(a, N)
|
|
print(type(result_arr))
|
|
print(result_arr) |