C Callback Function using ctypes

O

OJ

Hi I am opening a shared library which has defined the following
callback prototype:
extern void DebugMessage(int level, const char *message, ...);

My implementation in Python looks like this:
DEBUGFUNC = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.POINTER(ctypes.c_char))
def DebugMessage(lvl, msg):
print lvl, msg
return
debug_callback = DEBUGFUNC(DebugMessage)

Which gives me the following when running my python script:
0 <ctypes.LP_c_char object at 0x7f872d5148c0>
0 <ctypes.LP_c_char object at 0x7f872d5148c0>
0 <ctypes.LP_c_char object at 0x7f872d5148c0>
0 <ctypes.LP_c_char object at 0x7f872d5148c0>
0 <ctypes.LP_c_char object at 0x7f872d5148c0>
0 <ctypes.LP_c_char object at 0x7f872d5148c0>
0 <ctypes.LP_c_char object at 0x7f872d5148c0>
0 <ctypes.LP_c_char object at 0x7f872d5148c0>
0 <ctypes.LP_c_char object at 0x7f872d5148c0>
0 <ctypes.LP_c_char object at 0x7f872d5148c0>
0 <ctypes.LP_c_char object at 0x7f872d5148c0>
0 <ctypes.LP_c_char object at 0x7f872d5148c0>
0 <ctypes.LP_c_char object at 0x7f872d5148c0>

How can I get something useful?

If I change the print to:
print lvl, msg[0], it produces an Segfault
 
N

Nobody

Hi I am opening a shared library which has defined the following
callback prototype:
extern void DebugMessage(int level, const char *message, ...);

My implementation in Python looks like this:
DEBUGFUNC = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.POINTER(ctypes.c_char))
def DebugMessage(lvl, msg):
print lvl, msg
return
debug_callback = DEBUGFUNC(DebugMessage)

Which gives me the following when running my python script:
0 <ctypes.LP_c_char object at 0x7f872d5148c0>
How can I get something useful?

1. Use c_char_p instead of POINTER(c_char).
2. Use msg.value to obtain a Python string from the pointer.
 
O

OJ

If I change to c_char_p, my program segfaults.

If I use msg.value, I get this error message:
Traceback (most recent call last):
 File "_ctypes/callbacks.c", line 295, in 'calling callback function'
 File "./core.py", line 54, in DebugMessage
   print lvl, msg.value
AttributeError: 'LP_c_char' object has no attribute 'value'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top