Reputation: 81
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...
Upvotes: 0
Views: 566
Reputation: 613322
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.
Upvotes: 2