Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ctypes: initializing c_char_p()

I wrote a simple C++ program to illustrate my problem:

extern "C"{
    int test(int, char*);
}

int test(int i, char* var){
    if (i == 1){
        strcpy(var,"hi");
    }
    return 1;
}

I compile this into an so. From python I call:

from ctypes import *

libso = CDLL("Debug/libctypesTest.so")
func = libso.test
func.res_type = c_int

for i in xrange(5):
    charP = c_char_p('bye')
    func(i,charP)
    print charP.value

When I run this, my output is:

bye
hi
hi
hi
hi

I expected:

bye
hi
bye
bye
bye

What am I missing?

Thanks.

like image 548
Mark Avatar asked Dec 29 '22 08:12

Mark


2 Answers

The string which you initialized with the characters "bye", and whose address you keep taking and assigning to charP, does not get re-initialized after the first time.

Follow the advice here:

You should be careful, however, not to pass them to functions expecting pointers to mutable memory. If you need mutable memory blocks, ctypes has a create_string_buffer function which creates these in various ways.

A "pointer to mutable memory" is exactly what your C function expects, and so you should use the create_string_buffer function to create that buffer, as the docs explain.

like image 56
Alex Martelli Avatar answered Jan 13 '23 10:01

Alex Martelli


I am guessing python is reusing the same buffer for all 5 passes. once you set it to "hi", you never set it back to "bye" You can do something like this:

extern "C"{
    int test(int, char*);
}

int test(int i, char* var){
    if (i == 1){
        strcpy(var,"hi");
    } else {
        strcpy(var, "bye");
    }
    return 1;
}

but be careful, strcpy is just asking for a buffer overflow

like image 30
Evan Teran Avatar answered Jan 13 '23 11:01

Evan Teran