[Python-Dev] Baffled by PyArg_ParseTupleAndKeywords modification

Bengt Richter bokr at oz.net
Fri Feb 10 21:36:15 CET 2006


On Fri, 10 Feb 2006 18:02:03 +0100, =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= <martin at v.loewis.de> wrote:

>Jeremy Hylton wrote:
>> I admit that I'm also puzzled by Jack's specific question.  I don't
>> understand why an array passed to PyArg_ParseTupleAndKeywords() would
>> need to be declared as const.  I observed the problem in my initial
>> changes but didn't think very hard about the cause of the problem. 
>> Perhaps someone with better C/C++ standards chops can explain.
>
>Please take a look at this code:
>
>void foo(const char** x, const char*s)
>{
>        x[0] = s;
>}
>
>void bar()
>{
>        char *kwds[] = {0};
>        const char *s = "Text";
>        foo(kwds, s);
>        kwds[0][0] = 't';
>}
>
>If it was correct, you would be able to modify the const char
>array in the string literal, without any compiler errors. The
>assignment
>
>  x[0] = s;
>
>is kosher, because you are putting a const char* into a
>const char* array, and the assigment
>
>     kwds[0][0] = 't';
>
>is ok, because you are modifying a char array. So the place
>where it has to fail is the passing of the pointer-pointer.
>
Will a typedef help?

----< martin.c >-------------------------------------------
#include <cstdio>
typedef const char *ptext;
void foo(ptext *kw)
{
    const char *s = "Text";
    ptext *p;
    for(p=kw;*p;p++){ printf("foo:%s\n", *p);}
    kw[0] = s;
    for(p=kw;*p;p++){ printf("foo2:%s\n", *p);}
    kw[0][0] = 't';  /* comment this out and it compiles and runs */
    for(p=kw;*p;p++){ printf("foo3:%s\n", *p);}
}

int main()
{
    char *kwds[] = {"Foo","Bar",0};
    char **p;
    for(p=kwds;*p;p++){ printf("%s\n", *p);}
    foo(kwds);
    for(p=kwds;*p;p++){ printf("%s\n", *p);}
}
-----------------------------------------------------------
[12:32] C:\pywk\pydev>cl martin.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.

martin.c
martin.c(10) : error C2166: l-value specifies const object


But after commenting out:

[12:32] C:\pywk\pydev>cl martin.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.

martin.c
Microsoft (R) Incremental Linker Version 6.00.8168
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.

/out:martin.exe
martin.obj

[12:34] C:\pywk\pydev>martin
Foo
Bar
foo:Foo
foo:Bar
foo2:Text
foo2:Bar
foo3:Text
foo3:Bar
Text
Bar


Regards,
Bengt Richter



More information about the Python-Dev mailing list