from ctypes import *
msvcrt = cdll.msvcrt
message_string = "Hello world!\n"
msvcrt.printf("Testing: %s", message_string)
I'm going through a book about Ctypes and Python but the example code just doesn't work.
Could it be because the book was written for python 2 whereas I am on Python 3?
printf is only printing the first letter.
The built-in ctypes module is a powerful feature in Python, allowing you to use existing libraries in other languages by writting simple wrappers in Python itself. Unfortunately it can be a bit tricky to use. In this article we'll explore some of the basics of ctypes .
It is a big C++ codebase with a (very) thin python wrapper which uses CDLL to load the C++ and call some C functions that are available to allow primitive python scripting of the code.
The cubit, generally taken as equal to 18 inches (457 mm), was based on the length of the arm from the elbow to the tip of the middle finger and was considered the equivalent of 6 palms or 2 spans.
The C printf
function is expecting byte strings. In Python 3 all strings are unicode so you'll have to encode to bytes:
>>> msvcrt.printf("Testing: %s".encode('ascii'), message_string.encode('ascii'))
Testing: Hello world!
22
If you have any non-ascii characters then encode to the relevant windows codepage instead.
bleh, using "".encode('ascii') is ugly. You can often get away with just doing this:
TTF_OpenFont(b"assets/droid.ttf", 10)
^^
Note the 'b' type for the string. This is portable to python 2.7 as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With