Question about strings and pointers

Valentin Haenel <[email protected]>
Newsgroups gmane.comp.python.ctypes
Message-ID <[email protected]>
Hi,

i have been using ctypes quite happily over the last year or so, for a variety
of smaller projects. However last week i stumbled upon an issue that i was
unable to resolve. To spare you having to look through and understand the code
that i am wrapping i have written a small example to illustrate the type of
problem i am having:

Imagine i want to use the following funcion from ctypes:

void print_substring(char * first, char * after_last){
    char * current = first;
    while (current != after_last){
        putchar(*current);
        current = current + 1;
    }
    putchar('\n');

}

In this case first and after_last are pointers into the same memory block. An
exmaple use would be:

void main(void){
    char * string = "this is the substring we would like to print";
    print_substring(&string[12], &string[21]);
    return;
}

In this case first and after last are:

this is the substring we would like to print
            ^        ^

I have attempted to wrap this with the following python code:

from ctypes import *
lib = cdll.LoadLibrary('./libdemo-library.so.1')
lib.print_substring.argtypes = [POINTER(c_char), POINTER(c_char)]
test = "this is the substring we would like to print"
lib.print_substring(pointer(c_char(test[12])),pointer(c_char(test[21])))

But as you already guess this does not work. From what i understand the two
pointers don't point into the same string but into freshly allocated instances
of c_char, although i might be mistaken about that.  In any case  the code will
just print a load of garbage from memory and eventually segfault. I just can't
figure out how to obtain these two pointers to differnt positions in the same
string in ctypes.

If you want to play around with the code, please find it attached (includes
makefile).

Thanks in advance for your advice.

V-

------------------------------------------------------------------------------
The Planet: dedicated and managed hosting, cloud storage, colocation
Stay online with enterprise data centers and the best network in the business
Choose flexible plans and management services without long-term contracts
Personal 24x7 support from experience hosting pros just a phone call away.
http://p.sf.net/sfu/theplanet-com

_______________________________________________
ctypes-users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/ctypes-users
ctypes-string-demo.tgz (application/x-gtar, 704 B) - not displayed
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.