access string data from within cython

  • Thread starter Diez B. Roggisch
  • Start date
D

Diez B. Roggisch

Hi,

I'm trying to wrap a C-API which has a call that takes a void* and a size_t
as arguments.

void foo(void *data, size_t length)


The wrapper is supposed to be called with a python (byte)string instance,
which might contain more than one '\0'-character.

So how do I access the raw data of a string? I tried looking into the
buffer-protocol, but to be honest - that's beyond me, I don't see where
that is actually giving me access to the real data.

Diez
 
P

Philip Semanchuk

Hi,

I'm trying to wrap a C-API which has a call that takes a void* and a
size_t
as arguments.

void foo(void *data, size_t length)


The wrapper is supposed to be called with a python (byte)string
instance,
which might contain more than one '\0'-character.

So how do I access the raw data of a string? I tried looking into the
buffer-protocol, but to be honest - that's beyond me, I don't see
where
that is actually giving me access to the real data.

Hi Diez,
Would ctypes.create_string_buffer() work for you?


bye
P
 
S

sturlamolden

void foo(void *data, size_t length)

The wrapper is supposed to be called with a python (byte)string instance,
which might contain more than one '\0'-character.

So how do I access the raw data of a string?

cdef extern void foo(void *data, int length)
cdef char *data
cdef int length
bytestring = ... #whatever

rawdata = <char *> bytestring
length = <int> len(bytestring)

foo(data, length)
 
D

Diez B. Roggisch

Philip said:
Hi Diez,
Would ctypes.create_string_buffer() work for you?

I'm not using ctypes because I want a distributable egg with static
linkage. ctypes can't help there afaik.

Diez
 
D

Diez B. Roggisch

sturlamolden said:
cdef extern void foo(void *data, int length)
cdef char *data
cdef int length
bytestring = ... #whatever

rawdata = <char *> bytestring
length = <int> len(bytestring)

And that gives me the *full* bytestring, not only until the first zero?
I can't try that right now (not at work anymore), but if it's that easy,
that would be great.

Diez
 
S

sturlamolden

And that gives me the *full* bytestring, not only until the first zero?
I can't try that right now (not at work anymore), but if it's that easy,
that would be great.

It should, and if it does not it is a bug in Cython. The len()
function should work similarly in Python and Cython: It should just
call the object's __len__ method. Cython has no idea that your Python
object bytestring is a byte string, nor does Cython care.
10
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top