0

python ctypes cast get null string

b is address

if b_v.value is a common character, this is normal. But if b's content is hex like "1122001314" Long as it contains hex "00" the result maybe is 1122 the 001314 should be lose

Now I want get all content "1122001314". Please give me some method thanks.

the code is:

b_v=ctypes.cast(b,ctypes.POINTER(ctypes.c_char_p))

print binascii.b2a_hex(b_v.value)

example:

import ctypes
import binascii

va=binascii.a2b_hex('1212273031003535')
tt=ctypes.create_string_buffer(va)
b=ctypes.addressof(tt)
b_v=ctypes.cast(b,ctypes.c_char_p)
print binascii.b2a_hex(b_v.value)

now the result is :"1212273031"

i want the result is "1212273031003535"

2
  • 1
    Weclome to Stackoverflow. Please try to improve the wording on your question, or give a concrete code-example that illustrates what you want (input and expected output). It is very hard to understand your question. Commented Aug 23, 2012 at 7:03
  • the example code has be complementaryd Commented Aug 23, 2012 at 7:15

1 Answer 1

2

In the line tt=ctypes.create_string_buffer(va) You are building a string_buffer from a hexadecimal representation of data (binary data) and It's wrong, because c string terminates with first 0-value character. So your data breaks. Fortunately ctypes serves raw-data in addition to string value, so with tt.raw you can access your original data and you can use binascii.b2a_hex(tt.raw), but I'm not sure It's useful for you or not.

If you want to run b=ctypes.addressof(tt) and pass the address to somewhere else and then retrieve data from address by b_v=ctypes.cast(b,ctypes.c_char_p), I should say It's not possible with string_buffer type because your data is not text, It's a binary data and you can't store it in a string_buffer and then access to it with It's address.

You can retrieve data with knowing b if you know length of data too, Try this:

b, l = ctypes.addressof(tt), len(tt) - 1 # l - 1, because there is one extra byte for terminator NULL

#Somewhere else:
b_v=ctypes.cast(b, ctypes.POINTER(ctypes.c_char * l))
print binascii.b2a_hex(b_v.contents)
Sign up to request clarification or add additional context in comments.

9 Comments

binascii.b2a_hex(tt.raw) is useful but Only through b get content
b_v=ctypes.cast(b,ctypes.c_char_p) and this line can be changed
You can retrieve data using b, If and only if you know length of data, I had added an example to my answer
very very very thanks MostafaR thanks your method is usefull i love you ^_^
you could also try: type(tt).from_address(b) though it leaves terminating NUL in the data
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.