Проблемы с использованием кода C в Python | Комплект 2

Опубликовано: 12 Апреля, 2022

Предварительное условие: проблемы с использованием кода C в Python | Комплект 1

The DoubleArrayType class can handle the situation of Python having different forms like array, numpy array, list, tuple. In this class, a single method from_param() is defined. This method takes a single parameter and narrow it down to a compatible ctypes object (a pointer to a ctypes.c_double, in the example).

In the code below, the typename of the parameter is extracted and used to dispatch to a more specialized method. For example, if a list is passed, the typename is list and a method from_list() is invoked. For lists and tuples, the from_list() method performs a conversion to a ctypes array object.

Code #1 :

nums = [1, 2, 3]
a = (ctypes.c_double * len(nums))(*nums)
print ("a : ", a)
  
print (" a[0] : ", a[0])
  
print (" a[1] : ", a[1])
  
print (" a[2] : ", a[2])

Выход :

a : <__main__.c_double_Array_3 object at 0x10069cd40>

a[0] : 1.0

a[1] : 2.0

a[2] : 3.0

 
The from_array() method extracts the underlying memory pointer and casts it to a ctypes pointer object for array objects.

Code #2 :

import array
arr = array.array("d", [1, 2, 3])
print ("arr : ", arr)
  
ptr_ = a.buffer_info()
print (" ptr :", ptr)
  
print (" ", ctypes.cast(ptr, ctypes.POINTER(ctypes.c_double)))

Выход :

arr: array ('d', [1.0, 2.0, 3.0])

ptr: 4298687200

<__ main __. LP_c_double объект в 0x10069cd40> 

 
The from_ndarray() shows comparable conversion code for numpy arrays. By defining the DoubleArrayType class and using it in the type signature of avg(), the function can accept a variety of different array-like inputs.

Code #3 :

# libraries
import sample
import array
import numpy
  
print("Average of list : ", sample.avg([1, 2, 3]))
  
print(" Average of tuple : ", sample.avg((1, 2, 3)))
  
print( Average of array : ", sample.avg(array.array("d", [1, 2, 3])))
  
print( Average of numpy array : ", sample.avg(numpy.array([1.0, 2.0, 3.0])))

Выход :

Среднее значение списка: 2.0

Среднее значение кортежа: 2,0 

Среднее значение массива: 2,0

Среднее значение массива numpy: 2,0


Чтобы работать с простой структурой C, просто определите класс, содержащий соответствующие поля и типы, как показано в приведенном ниже коде. После определения можно использовать класс в сигнатурах типов, а также в коде, который должен создавать экземпляры и работать со структурами.

Code #4 :

class Point(ctypes.Structure):
    _fields_ = [("x", ctypes.c_double),
                ("y", ctypes.c_double)]
  
point1 = sample.Point(1, 2)
point2 = sample.Point(4, 5)
  
print ("pt1 x : ", point1.x)
  
print (" pt1 y : ", point1.y)
  
print (" Distance between pt1 and pt2 : ",
           sample.distance(point1, point2))

Выход :

pt1 x: 1.0

pt1 y: 2.0

Расстояние между точками 1 и 2: 4,242640687119285

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.