Re: How to get binary data to callback function

Nikolaus Rath <[email protected]>
Newsgroups gmane.comp.python.ctypes
Message-ID <[email protected]>
Peter Silva <[email protected]> writes:
> On Tue, Dec 22, 2009 at 6:13 PM, Nikolaus Rath <[email protected]> wrote:
>
>> Hello,
>>
>> When I define a callback function with a prototype of
>>
>>   ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_int)
>>
>> The function receives a true Python string. However, my data isn't
>> actually \0 terminated, and I would like to call string_at(par1, par2)
>> to get the binary data. But how do I get ctypes to pass the c_char_p
>> object to my function, rather than the unwrapped string?
>>
>
> is this what you mean?
>
> these are pre-allocating space for a return value to be filled by the C
> function:
>
>     sense_buffer = create_string_buffer(64)
>     self.mx_sb_len = len(sense_buffer)
>     #io_hdr.sbp=addressof(sense_buffer)
>     io_hdr.sbp=cast(sense_buffer,c_char_p)
>     io_hdr.sb_len_wr = 0 # initialize just in case...
>
>     page_buffer=create_string_buffer(sz)
>     io_hdr.dxfer_len = sz
>     #io_hdr.dxferp = addressof(page_buffer)
>     io_hdr.dxferp = cast(page_buffer,c_char_p)
>
>     if self.debug & Drobo.DBG_HWDialog:
>       print "4 before ioctl, sense_buffer_len=", io_hdr.mx_sb_len
>
>     i=ioctl(self.sg_fd, sg_io_hdr.SG_IO, io_hdr)

I think that's not what I mean, because I don't want to preallocate
anything. But I'm not sure, because I don't understand your code (I don't even
see any callback function being called).

Here is a short example that demonstrates my problem.

C-Library:

#include <stdio.h>
typedef void cb_fun(char*, int);
void callback(cb_fun* f) {
    char* c = "Hello\0World";
    int len = 11;
    
    (*f)(c, len);
}


Python code:

from ctypes import *
lib = CDLL('./lib.so')
def test(buf, len):
    print buf
    print string_at(buf, len)
lib.callback.restype = None
lib.callback(CFUNCTYPE(None, c_char_p, c_int)(test))


When 'test' is called, it prints 'Hello' two times. What I want it to
print is 'Hello\0World'.


Best,

   -Nikolaus

-- 
 »Time flies like an arrow, fruit flies like a Banana.«

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C


------------------------------------------------------------------------------
This SF.Net email is sponsored by the Verizon Developer Community
Take advantage of Verizon's best-in-class app development support
A streamlined, 14 day to market process makes app distribution fast and easy
Join now and get one step closer to millions of Verizon customers
http://p.sf.net/sfu/verizon-dev2dev 
_______________________________________________
ctypes-users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/ctypes-users
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.