Showing posts with label Using C with Python. Show all posts
Showing posts with label Using C with Python. Show all posts

Sunday, September 24, 2017

How to Use C Programming Language with Python



C is one of the first programming language a programmer should learn. But the syntax of the language and semicolons make it hard. But C is the most powerful language ever created. So, we want to use power of C in python and python provides a very good way to do so.

On windows the C runtime is msvcrt.dll which is located in C:\Windows\System32 and on linux it is libc.so.6. We will write a code in Windows and see the result. So Let us C -


from ctypes import *
msvcrt=cdll.msvcrt
message_string="My Name is Anthony\n"
msvcrt.printf("Testing %s",message_string)

In the above code we import all the modules of ctypes, which is responsible for using C in python. Then assign a variable to the dll we need to run the code in the second line. Next, the string we want to print. In the next statement we use pure C function printf() to print our message.

Similarly for Linux OS we need to do a little change. Just replace the second statement to have that libc.so.6. e.g.


from ctypes import *
libc = CDLL("libc.so.6")
message_string="My Name is Anthony\n"
msvcrt.printf("Testing %s",message_string)

That's all for today. In the next entry we'll learn about structure and Union.

(ref: Gray Hat Python)

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...