0

After following this answer, I wrote a C library which I call from python using ctypes. The C library contains a function which takes a char* and modifies its contents. I would like to read the contents in Python, however, after calling the library function in Python, I get an empty string even though I see the correct output in the terminal if I include a printf statement in the C code. What am I doing wrong?

C code:

void somefunction(char * pythonbuffer)
{
    /* do something */
    printf("%s", pythonbuffer);
}

Python code:

lib.somefunction.argtypes = [ctypes.c_char_p] 
lib.somefunction.restype = ctypes.c_void_p 

buffer = ctypes.create_string_buffer(upper_limit)

lib.somefunction(buffer)

print(buffer.value)

Output: b''

5
  • How exactly does somefunction modify its parameter pythonbuffer? What did you expect to see happen? Commented Jun 21, 2017 at 17:57
  • It calls another library which stores a long string in pythonbuffer. If I then print the content in C I get what I expect, but I can't get the same output in Python. Commented Jun 21, 2017 at 18:06
  • 1
    i guess you want lib.somefunction(ctypes.POINTER(buffer)) Commented Jun 21, 2017 at 18:14
  • @Coldspeed, POINTER(buffer) makes no sense, and pointer(buffer) would be redundant. Commented Jun 21, 2017 at 19:14
  • @Coldspeed , if you look at this the buffer should be passed as is. Commented Jun 22, 2017 at 8:48

1 Answer 1

1

Found the problem. Turns out that the code in the /* do something */ part somehow changed the adress of pythonbuffer. I solved it by using a temporary char * and then copying it to pythonbuffer with strcpy.

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

2 Comments

Remember to fix restype to be None instead of returning a garbage c_void_p pointer.
Yep, I did that.

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.