1

I have c++ library, functions of which are called from python side. One of the functions gets a pointer on an array, which on python side has values in [0:255] and defined as

 seq1=numpy.array(image,dtype=numpy.uint8).flatten()
 seq=numpy.zeros((w*h*3),dtype=numpy.uint8)

the function call goes as

myCppFunction(ctypes.c_void_p(seq.ctypes.data),
                     ctypes.c_void_p(seq1.ctypes.data), 
...)

on C++ side the function defined as

void myCppFunction(ushort *seq, ushort *sequence1, ...)

When I simply print what I receive on C++ side as seq, sequence1, I'm getting values far above unsigned short range and zeros sequence is not filled with zeros. Compilation goes fine but a real run results in segmentation fault. Where I'm wrong?

1
  • Your first problem here is almost certainly what @WarrenWeckesser pointed out, that you're treating an array of 1-byte values as if they were 2-byte values. But on top of that, note that ctypes.data "may contain data that is not aligned, or not in the correct byte-order… may not even be writable." In other words, even if it were a uint16 array, you can't just pass it to a ushort * without checking anything. Commented Jan 24, 2013 at 21:41

1 Answer 1

3

ushort is 2 bytes, and numpy.uint8 is 1 byte.

Sign up to request clarification or add additional context in comments.

4 Comments

@Jaime: Sure it would. Imagine a very simple 2x2 image. So, seq.ctypes.data is an array of four uint8 values: [00, 00, 00, 00] (in hex). When you interpret that are an array of four ushort values, it's [0000, 0000, <random garbage>, <random garbage>]. That random garbage is whatever happens to be next on the heap, which can easily be nonzero values. (Or, of course, it can go past the end of the allocated region and segfault.)
Are the first (w*h*3)/2 values zero?
@abanert Yes, I fully agree. My poorly expressed point was that you should still see some zeros.
you are right about the bytes mismatch, I have to change ushort on unsigned char (images correspond to numpy.uint8, so this has to be kept). Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.