0

I want to pass the reference to a string from python to a c program. The c program writes something to the string and I want to read it back in python. The c program looks like:

void foo(char *name) {
    name = "Hello World";
}

And the Python script:

>>> import ctypes
>>> lib=ctypes.CDLL('libfoo.so')
>>> name=ctypes.create_string_buffer(32)
>>> print name.value

>>> lib.foo(name)
>>> print name.value

>>>

I'd expect "Hello World" after the second print. I'm sure it's simple, but I can't figure out what's wrong...

1 Answer 1

2

Your C code changes the value of the pointer, rather than changing the buffer. Remember that C parameters are passed by value so modifying a parameter can never result in changes that can be seen by the caller.

Anyway, you just need to use strcpy to copy your string into the buffer provided.

void foo(char *name) {
    strcpy(name, "Hello World");
}

Obviously in real code you'll want to pass the buffer length too so that you can avoid buffer overruns.

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

Comments

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.