Issues with using C code in Python | Set 2
Last Updated :
20 Mar, 2019
Prerequisite:
Issues with using C code in Python | Set 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 :
Python3 1==
nums = [1, 2, 3]
a = (ctypes.c_double * len(nums))(*nums)
print ("a : ", a)
print ("\na[0] : ", a[0])
print ("\na[1] : ", a[1])
print ("\na[2] : ", a[2])
Output :
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 :
Python3 1==
import array
arr = array.array('d', [1, 2, 3])
print ("arr : ", arr)
ptr_ = a.buffer_info()
print ("\nptr :", ptr)
print ("\n", ctypes.cast(ptr, ctypes.POINTER(ctypes.c_double)))
Output :
arr : array('d', [1.0, 2.0, 3.0])
ptr : 4298687200
<__main__.LP_c_double object at 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 :
Python3 1==
# libraries
import sample
import array
import numpy
print("Average of list : ", sample.avg([1, 2, 3]))
print("\nAverage of tuple : ", sample.avg((1, 2, 3)))
print(\nAverage of array : ", sample.avg(array.array('d', [1, 2, 3])))
print(\nAverage of numpy array : ", sample.avg(numpy.array([1.0, 2.0, 3.0])))
Output :
Average of list : 2.0
Average of tuple : 2.0
Average of array : 2.0
Average of numpy array : 2.0
To work with a simple C structure, simply define a class that contains the appropriate fields and types as shown in the code below. After defining, the class in type signatures as well as in code that needs to instantiate and work with the structures, can be used.
Code #4 :
Python3 1==
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 ("\npt1 y : ", point1.y)
print ("\nDistance between pt1 and pt2 : ",
sample.distance(point1, point2))
Output :
pt1 x : 1.0
pt1 y : 2.0
Distance between pt1 and pt2 : 4.242640687119285
Similar Reads
Issues with using C code in Python | Set 1 Prerequisite: Using C codes in Python | Set 1, Set 2 Issue #1 : If using ctypes then there is a problem that the original C code may use language that donât map cleanly to Python. Let's take the example of divide() function as it returns a value through one of its arguments. It is a common C techniq
2 min read
Using C codes in Python | Set 2 Prerequisite: Using C codes in Python | Set 1 In the previous article, we have discussed how to access C code in Python. Now, let's see how to access C functions. Code #1 : Accessing C functions with Python Python3 1== import work print ("GCD : ", work.gcd(35, 42)) print ("\ndivide :
2 min read
Using C codes in Python | Set 1 Prerequisite: How to Call a C function in Python Let's discuss the problem of accessing C code from Python. As it is very evident that many of Pythonâs built-in libraries are written in C. So, to access C is a very important part of making Python talk to existing libraries. There is an extensive C p
4 min read
C strings conversion to Python For C strings represented as a pair char *, int, it is to decide whether or not - the string presented as a raw byte string or as a Unicode string. Byte objects can be built using Py_BuildValue() as C // Pointer to C string data char *s; // Length of data int len; // Make a bytes object PyObject *ob
2 min read
Python | C Strings of Doubtful Encoding | Set-2 String handling in extension modules is a problem. C strings in extensions might not follow the strict Unicode encoding/decoding rules that Python normally expects. Thus, itâs possible that some malformed C data would pass to Python. A good example might be C strings associated with low-level system
3 min read
Using Pointers in Python using ctypes In this article, we are going to learn about using pointers in Python using ctypes module. We will see how we can use Pointers in Python programming language using the ctypes module. Some basic operations like storing addresses, pointing to a different variable using pointers, etc. will be demonstra
10 min read
Wrapping C/C++ for Python using SWIG - Set 1 There is no doubt that C is faster than Python then how do Python library like Numpy perform huge number crunching job so fast and efficiently? Actually, libraries like Numpy are not completely written in Python instead, some parts of the library are written in C which provides performance boost. Af
5 min read
Python | Set 3 (Strings, Lists, Tuples, Iterations) In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. Strings in Python: A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quo
3 min read
Python | C Strings of Doubtful Encoding | Set-1 One can convert strings between C and Python vice-versa but the C encoding is of a doubtful or unknown nature. Let's suppose that a given C data is supposed to be UTF-8, but itâs not being strictly enforced. So, it is important to handle such kind of malformed data so that it doesnât crash Python or
2 min read
C Extension Module using Python Writing a simple C extension module directly using Pythonâs extension API and no other tools. It is straightforward to make a handcrafted extension module for a simple C code. But first, we have to make sure that the C code has a proper header file. Code #1 : C #include <math.h> extern int gcd
4 min read