Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing strings to ctypes functions under Python 3.x

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.

like image 332
Edward Avatar asked Dec 17 '11 04:12

Edward


People also ask

Is ctypes a built in Python?

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 .

What is CDLL in Python?

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.

What is C_ubyte?

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.


2 Answers

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.

like image 174
Duncan Avatar answered Nov 02 '22 12:11

Duncan


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.

like image 23
Doug Avatar answered Nov 02 '22 12:11

Doug