3.字符串 ngx_string、ngx_null_string 、ngx_set_string、ngx_str_null

#define ngx_string(str)     { sizeof(str) - 1, (u_char *) str }
#define ngx_null_string     { 0, NULL }
#define ngx_str_set(str, text)    \
    (str)->len = sizeof(text) - 1; (str)->data = (u_char *) text
#define ngx_str_null(str)   (str)->len = 0; (str)->data = NULL

實例

  #include <stdio.h>
  #include <ngx_config.h>
  #include <ngx_conf_file.h>
  #include <nginx.h>
  #include <ngx_core.h>
  #include <ngx_string.h>
  #include <ngx_palloc.h>
  
  volatile ngx_cycle_t *ngx_cycle;
  
  void ngx_log_error_core(ngx_uint_t level, ngx_log_t *log, ngx_err_t err,
    const char *fmt, ...)
  {
  }
  
  int
  main(int argc, char *argv[])
  {
    ngx_str_t t1 = ngx_string("bei jing");
    ngx_str_t t2 = ngx_null_string;
  
    printf("t1:\n");
    printf("t1.len = %lu\n", t1.len);
    printf("t1.data = %s\n\n", t1.data);
  
    printf("t2:\n");
    printf("t2.len = %lu\n", t2.len);
    printf("t3.data = %s\n\n\n", t2.data);
  
    ngx_str_null(&t1);
    ngx_str_set(&t2, "shang hai");
  
    printf("t1:\n");
    printf("t1.len = %lu\n", t1.len);
    printf("t1.data = %s\n\n", t1.data);
  
    printf("t2:\n");
    printf("t2.len = %lu\n", t2.len);
    printf("t3.data = %s\n", t2.data);

    return 0;
 }

執行:

gcc -c -O -pipe -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Wunused-function -Wunused-variable -Wunused-value -Werror -g 
    -I ../../objs/ 
    -I ../os/unix/ 
    -I../core/ 
    -I /usr/local/opt/pcre/include/ 
    -I../event/ 
    -I../os/ 
    ./j_str.c -o ./j_str.o

gcc -o ./j_str ./j_str.o 
    ../../objs/src/core/ngx_string.o       
    ../../objs/src/os/unix/ngx_alloc.o 
    ../../objs/src/core/ngx_palloc.o

結果:

t1:
t1.len = 8
t1.data = bei jing

t2:
t2.len = 0
t3.data = (null)


t1:
t1.len = 0
t1.data = (null)

t2:
t2.len = 9
t3.data = shang hai
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容