Krustenkaese
Krustenkaese

Reputation: 155

Python - Passing character to C library

I've got quite the trouble running a program on Linux i wrote. Since it's quite a large program i won't post the whole code but only the part that gets me confused. I've got a library, written in C++ and compiled on Linux Ubuntu, which does some work and prints an incoming character to the console like this:

bool PostCommand( void* pParam, char c, char* szRet, int nLength, int nBlockTime )
{
    printf("Got: %d", c);
    //do some work
    return true;
}

The whole thing compiles well and my Python program is able to call the function:

# -*- coding: ascii -*-
from ctypes import cdll,c_char,create_string_buffer,...#don't want to list 'em all
m_DLL = cdll.LoadLibrary("./libaddonClient.so")
PostCommand = m_DLL.PostCommand
PostCommand.argtype = [c_void_p,c_char,c_char_p,c_int,c_int]
PostCommand.restype = c_bool

print ord('1')
sz = create_string_buffer(20);
#pObject was generated prior and works fine
PostCommand( pObject, '1', sz, 20, 1 )

The console output looks like

49
Got: -124

My question is how the 49 could change into -124. The variable isn't being changed between it's creation and the call of the C++ function or the printf, which follows right after the call. There are no threads accessing this function nor static variables.

Upvotes: 1

Views: 57

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53046

Your problem is in the python code, you are passing a string instead of a character, the single quotes and double quotes both work almost exactly the same in python, and -124 I presume comes perhaps from something that python interpreter does internally, try this

PostCommand( pObject, ord('1'), sz, 20, 1 )

What is very likely happening is that the parameter when processed by the interpreter is stored as a c string, which is a nul terminated sequence of non-nul bytes, hence a pointer is almost surely used, so -124 has to be the address of the pointer which of course requires more than a byte to be represented.

Upvotes: 1

Related Questions