BewareMyPower commented on PR #294:
URL: 
https://github.com/apache/pulsar-client-cpp/pull/294#issuecomment-1619783898

   In addition, I don't think use a null-terminated string as the tableview 
value is good for C API. The value is actually a byte array rather than a 
null-terminated string. Unlike the `TableView` class, it's okay to return a 
`std::string`, which is actually a byte array in C++. For example, if the 
producer sends 4 bytes: `[0x01, 0x00, 0x02, 0x00]`, you can never know the 
length.
   
   ```c
   #include <stdio.h>
   #include <stdlib.h>
   #include <string.h>
   
   static void get_value(char **value) {
     char *data = (char *)malloc(4);
     data[0] = 0x01;
     data[1] = 0x00;
     data[2] = 0x02;
     data[3] = 0x00;
     *value = data;
   }
   
   int main(int argc, char *argv[]) {
     char *value;
     get_value(&value);
     printf("length: %zu\n", strlen(value));
     return 0;
   }
   ```
   
   The code example is a demo to show the difference between a byte array and a 
null-terminated string.
   
   So it's better to add a length parameter like:
   
   ```c
   #include <stdio.h>
   #include <stdlib.h>
   
   static void get_value(char **value_ptr, size_t *value_len) {
     char *data = (char *)malloc(4);
     data[0] = 0x01;
     data[1] = 0x00;
     data[2] = 0x02;
     data[3] = 0x00;
     *value_ptr = data;
     *value_len = 4;
   }
   
   int main(int argc, char *argv[]) {
     char *value;
     size_t len;
     get_value(&value, &len);
     printf("length: %zu\n", len);
     for (size_t i = 0; i < len; i++) {
       printf("0x%02x%c", value[i], (i < len - 1) ? ' ' : '\n');
     }
     return 0;
   }
   ```
   
   Output:
   
   ```
   length: 4
   0x01 0x00 0x02 0x00
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to