Trouble understanding how to process C string

后端 未结 4 1361
粉色の甜心
粉色の甜心 2021-01-27 07:13

I\'m trying to use Mac OS X\'s listxattr C function and turn it into something useful in Python. The man page tells me that the function returns a string buffer, which is a \"si

相关标签:
4条回答
  • 2021-01-27 07:40

    Actually, since I'm going to send it to Python I don't have to process it C-style after all. Just use the Py_BuildValue passing it the format character s#, which knows what do with it. You'll also need the size.

    return Py_BuildValue("s#", buffer, size);
    

    You can process it into a list on Python's end using split('\x00'). I found this after trial and error, but I'm glad to have learned something about C.

    0 讨论(0)
  • 2021-01-27 07:46

    It looks like listxattr returns the size of the buffer it has filled, so you can use that to help you. Here's an idea:

    for(int i=0; i<res-1; i++)
    {
        if( buffer[i] == 0 )
            buffer[i] = ',';
    }
    

    Now, instead of being separated by null characters, the attributes are separated by commas.

    0 讨论(0)
  • 2021-01-27 07:56
    1. char *p = buffer;
    2. get the length with strlen(p). If the length is 0, stop.
    3. process the first chunk.
    4. p = p + length + 1;
    5. back to step 2.
    0 讨论(0)
  • 2021-01-27 08:01

    So you guessed pretty much right.

    The listxattr function returns a bunch of null-terminated strings packed in next to each other. Since strings (and arrays) in C are just blobs of memory, they don't carry around any extra information with them (such as their length). The convention in C is to use a null character ('\0') to represent the end of a string.

    Here's one way to traverse the list, in this case changing it to a comma-separated list.

    int i = 0;
    for (; i < res; i++)
       if (buffer[i] == '\0' && i != res -1) //we're in between strings
           buffer[i] = ',';
    

    Of course, you'll want to make these into Python strings rather than just substituting in commas, but that should give you enough to get started.

    0 讨论(0)
提交回复
热议问题