flashburn
flashburn

Reputation: 4528

python, C, ctypes and a strange character

I'm trying to figure out how to use C functions in a python code. It looks like by far the simplest solution is to use ctypes. However for some reason I see strange behavior after I create a library which I import to python. All the details are provided below.

Here is what I have for C code:

/* mymodule.c */
#include <stdio.h>
#include "mymodule.h"
void displayargs(int i, char c, char* s) {
  (void)printf("i = %d, c = %c, s = %s\n", i, c, s);
}

/* mymodule.h */
void displayargs(int i, char c, char* s)

I build a library out of it using the following commands:

gcc -Wall -fPIC -c mymodule.c
gcc -shared -Wl,-soname,libmymodule.so.1 -o libmymodule.so mymodule.o

My Python test code looks like this

#!/usr/bin/python

# mymoduletest.py
import ctypes

mylib = ctypes.CDLL('./libmymodule.so')
mylib.displayargs(10, 'c', "hello world!")

When I run ./mymoduletest.py I expect to see

i = 10, c = c, s = hello world!

however I see

i = 10, c = �, s = hello world!

Why character is displayed instead of an actual char value of c?

Any help is appreciated.

Upvotes: 0

Views: 70

Answers (1)

user2357112
user2357112

Reputation: 281585

You need to specify the function's argument and return types:

mylib.displayargs.argtypes = (ctypes.c_int, ctypes.c_char, ctypes.c_char_p)
mylib.displayargs.restype = None  # None means void here.

If you don't specify the types, Python has to guess, and the guess it makes when you pass a string is that the function wants a char *.

Upvotes: 1

Related Questions