zoukankan      html  css  js  c++  java
  • 可变参数以及stdcall

    void event_warnx(const char *fmt, ...) EV_CHECK_FMT(1,2);
    
    #define EV_CHECK_FMT(a,b) __attribute__((format(printf, a, b)))
    void
    event_debugx_(const char *fmt, ...)
    {
        va_list ap;
    
        va_start(ap, fmt);
        event_logv_(EVENT_LOG_DEBUG, NULL, fmt, ap);
        va_end(ap);
    }
    
    void
    event_logv_(int severity, const char *errstr, const char *fmt, va_list ap)
    {
        char buf[1024];
        size_t len;
    
        if (severity == EVENT_LOG_DEBUG && !event_debug_get_logging_mask_())
            return;
    
        if (fmt != NULL)
            evutil_vsnprintf(buf, sizeof(buf), fmt, ap);
        else
            buf[0] = '';
    
        if (errstr) {
            len = strlen(buf);
            if (len < sizeof(buf) - 3) {
                evutil_snprintf(buf + len, sizeof(buf) - len, ": %s", errstr);
            }
        }
    
        event_log(severity, buf);
    }
    event_log(int severity, const char *msg)
    {
        if (log_fn)
            log_fn(severity, msg);
        else {
            const char *severity_str;
            switch (severity) {
            case EVENT_LOG_DEBUG:
                severity_str = "debug";
                break;
            case EVENT_LOG_MSG:
                severity_str = "msg";
                break;
            case EVENT_LOG_WARN:
                severity_str = "warn";
                break;
            case EVENT_LOG_ERR:
                severity_str = "err";
                break;
            default:
                severity_str = "???";
                break;
            }
            (void)fprintf(stderr, "[%s] %s
    ", severity_str, msg);
        }
    }

    event_debugx("Connecting lime to coconut");的使用

     eg:

    1、__attribute__ format属性可以给被声明的函数加上类似printf或者scanf的特征,它可以使编译器检查函数声明和函数实际调用参数之间的格式化字符串是否匹配。format属性告诉编译器,按照printf, scanf等标准C函数参数格式规则对该函数的参数进行检查。在封装调试信息的接口时非常的有用

    2、va_list va_start va_end 作用原理:

    在函数中使用可变参数,要包含头文件<stdarg.h>。它包含以下几个宏:va_start;va_arg;va_end;va_copy。

      • VA_ARG宏,获取可变参数的当前参数,返回指定类型并将指针指向下一参数(t参数描述了当前参数的类型):
        #define va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)) )
      • VA_START宏,获取可变参数列表的第一个参数的地址(ap是类型为va_list的指针,v是可变参数最左边的参数):
        #define va_start(ap,v) ( ap = (va_list)&v + _INTSIZEOF(v) )
      • VSPRINT函数,vsprintf是sprintf的一个变形:
        #功能:送格式化输出到串中,返回值:正常情况下返回生成字串的长度(除去),错误情况返回负值
      • VA_END宏,清空va_list可变参数列表:
        #define va_end(ap) ( ap = (va_list)0 )

    C语言中函数参数的内存布局。首先,函数参数是存储在栈中的,函数参数从右往左依次压入;

    void test(char *para1,char *param2,char *param3, char *param4) { va_list list; ...... return; }

    在linux中,栈由高地址往低地址生长,调用test函数时,其参数入栈情况如下

    void PrintString(char*, ...);
    int main(void)
    { 
        PrintString("Msg","This","is","a","test!","");    
        return 0;
    }
    
    //ANSI标准形式的声明方式,括号内的省略号表示可选参数
    //利用va_start相关宏,获取参数列表中的所有参数,并打印
    void PrintString (char* prev_param, ...)
    {
        //定义保存函数参数的结构
        va_list pArgs; 
        int argNo = 0;
        char* para;    //获取参数用的临时变量    
    
        //对pArgs进行初始化,让它指向可变参数表里面的第一个参数
        //prev_param 是在变参表前面紧挨着的一个变量,即"..."之前的那个参数
        va_start(pArgs, prev_param); 
    
        while (1) 
        {
            //获取参数
            para = va_arg(pArgs, char*);
            if ( strcmp( para, "") == 0 )
                break; 
            printf("Parameter #%d is: %s
    ", argNo, para);
            argNo++;
        }
        
        //获取所有的参数之后,将pArgs指针关掉
        va_end(pArgs);        
    }

    _stdcall与_cdecl区别:

    实际上声明一个函数时应该告诉函数的调用方式,如下:

    typedef void (WINAPI *LPFUN)(void);

    typedef void (__stdcall *LPFUN)(void);

    typedef void    (FAR PASCAL *LPFUN)    (void);
    _cdecl是C和C++程序的缺省调用方式。每一个调用它的函数都包含清空堆栈的代码,
    所以产生的可执行文件大小会比调用_stdcall函数的大。函数采用从右到左的压栈方式;

      cdecl调用约定的参数压栈顺序是和stdcall是一样的,参数首先由右向左压入堆栈。所不同的是,函数本身不清理堆栈,调用者负责清理堆栈。由于这种变化,所以C调用约定允许函数的参数的个数是不固定的;在被调用函数 (Callee) 返回后,由调用方 (Caller) 调整堆栈。

     1. 调用方的函数调用                                       

    2. 被调用函数的执行

    3. 被调用函数的结果返回

    4. 调用方清除调整堆栈

    因为每个调用的地方都需要生成一段调整堆栈的代码,所以最后生成的文件较大。

    函数的参数个数可变(就像 printf 函数一样),因为只有调用者才知道它传给被调用函数几个参数,才能在调用结束时适当地调整堆栈。

    stdcall在被调用函数 (Callee) 返回前,由被调用函数 (Callee) 调整堆栈

    1. 调用方的函数调用

    2. 被调用函数的执行

    3. 被调用函数清除调整堆栈

    4. 被调用函数的结果返回   

     因为调整堆栈的代码只存在在一个地方(被调用函数的代码内),所以最后生成的文件较小。

    注意:

    2.Variadic Macros: ... and _ _VA_ARGS_ _

    Some functions, such as printf(), accept a variable number of arguments. The stdvar.h header file,provides tools for creating user-defined functions with a variable number of arguments. And C99 does the same thing for macros.Although not used in the standard, the word variadic has come into currency to label this facility. (However, the process that has added stringizing and variadic to the C vocabulary has not yet led to labeling functions or macros with a fixed number of arguments as fixadic functions and normadic macros.)

    The idea is that the final argument in an argument list for a macro definition can be ellipses (that is, three periods)(省略号). If so, the predefined macro _ _VA_ARGS_ _ can be used in the substitution part to indicate what will be substituted for the ellipses. For example, consider this definition:

    #define PR(...) printf(_ _VA_ARGS_ _)

    Suppose you later invoke the macro like this:

    PR("Howdy");

    PR("weight = %d, shipping = $%.2f ", wt, sp);

    For the first invocation, _ _VA_ARGS_ _ expands to one argument:

    "Howdy"

    For the second invocation, it expands to three arguments:

    "weight = %d, shipping = $%.2f ", wt, sp

    Thus, the resulting code is this:

    printf("Howdy");

    printf("weight = %d, shipping = $%.2f ", wt, sp);

    #define VLOG_FATAL(...) vlog_fatal(THIS_MODULE, __FILE__, __LINE__, __func__, __VA_ARGS__)
    
    void
    vlog_fatal(const struct vlog_module *module, const char *file, int lineno,
                      const char *func, const char *message, ...)
    {
        va_list args;
    
        va_start(args, message);
        vlog_fatal_valist(module, file, lineno, func, message, args);
        va_end(args);
    }
    /* Writes 'message' to the log at the given 'level' and as coming from the
     * given 'module'.
     *
     * Guaranteed to preserve errno. */
    extern int get_telnet_level(void);
    void
    vlog_valist(const struct vlog_module *module, enum vlog_level level,
                const char *file, int lineno, const char *func,
                const char *message, va_list args)
    {
        bool log_to_console = module->levels[VLF_CONSOLE] >= level;
        bool log_to_syslog = module->levels[VLF_SYSLOG] >= level && syslog_fd >= 0;
        bool log_to_file = module->levels[VLF_FILE] >= level && log_fd >= 0;
        int xxx_log_level = get_telnet_level();
    
        if (s_log_enable) {
            if (level <= VLL_WARN) {
                xxxx_alarm_log(func, lineno, message, args);
            }
            if (s_log_enable) {
                switch(level) 
                {
                case VLL_OFF:
                case VLL_EMER:
                case VLL_ALARM:
                case VLL_ERR:
                case VLL_WARN:
                case VLL_INFO:
                case VLL_DBG:
                    if (get_telnet_level()) {
                        xxx_vlog_output(TO_TELNET, ET_DEBUG, 0, basename(file), lineno, func, 0, 0, message, args);
                    }
                    break;
                case VLL_KEYEVENT:
                    xxx_vlog_output(TO_LOGS, ET_WARN, 0, basename(file), lineno, func, 0, 0, message, args);
                    break;
                default:
                    // unknown level, do nothing
                    break;
                }
            }
        }
            
        if ((log_to_console && !s_log_enable) || log_to_syslog || log_to_file) {
            int save_errno = errno;
            struct ds s;
    
            vlog_init();
    
            ds_init(&s);
            ds_reserve(&s, 1024);
            ++*msg_num_get();
    
            ovs_rwlock_rdlock(&pattern_rwlock);
            if (log_to_console) {
                format_log_message(module, level,
                                   destinations[VLF_CONSOLE].pattern, message,
                                   args, &s);
                ds_put_char(&s, '
    ');
                fprintf(stderr, "[%s %s:%d]", func, basename(file), lineno);
                fputs(ds_cstr(&s), stderr);
            }
    
            if (log_to_syslog) {
                int syslog_level = syslog_levels[level];
                char *save_ptr = NULL;
                char *line;
                int facility;
    
                format_log_message(module, level, destinations[VLF_SYSLOG].pattern,
                                   message, args, &s);
                for (line = strtok_r(s.string, "
    ", &save_ptr); line;
                     line = strtok_r(NULL, "
    ", &save_ptr)) {
                    atomic_read_explicit(&log_facility, &facility,
                                         memory_order_relaxed);
                    syslogger->class->syslog(syslogger, syslog_level|facility, line);
                }
    
                if (syslog_fd >= 0) {
                    format_log_message(module, level,
                                       "<%B>1 %D{%Y-%m-%dT%H:%M:%S.###Z} "
                                       "%E %A %P %c - xefxbbxbf%m",
                                       message, args, &s);
                    send_to_syslog_fd(ds_cstr(&s), s.length);
                }
            }
    
            if (log_to_file) {
                format_log_message(module, level, destinations[VLF_FILE].pattern,
                                   message, args, &s);
                ds_put_char(&s, '
    ');
    
                ovs_mutex_lock(&log_file_mutex);
                if (log_fd >= 0) {
                    if (log_writer) {
                        async_append_write(log_writer, s.string, s.length);
                        if (level == VLL_EMER) {
                            async_append_flush(log_writer);
                        }
                    } else {
                        ignore(write(log_fd, s.string, s.length));
                    }
                }
                ovs_mutex_unlock(&log_file_mutex);
            }
            ovs_rwlock_unlock(&pattern_rwlock);
    
            ds_destroy(&s);
            errno = save_errno;
        }
    }

     重要:

    1) va_start和va_end须配对使用;
    2) va_copy和va_end须配对使用;

    ##__VA_ARGS__ 宏前面加上##的作用在于,当可变参数的个数为0时,这里的##起到把前面多余的","去掉的作用,否则会编译出错

    一般这个用在调试信息上多一点

    例如:

    #define test_print1(fmt,...)  printf(fmt,__VA_ARGS__)  
    
    test_print2("iiiiiii
    ")       编译失败打印,因为扩展出来只有一个参数,至少要两个及以上参数
    
    如果是#define test_print2(fmt,...)  printf(fmt,##__VA_ARGS__)  




  • 相关阅读:
    CLSCompliantAttribute
    杂言
    批处理修改目录的隐藏属性
    unittest基本用法
    unittest跳过用例
    MySQL流程控制结构
    MySQL视图
    MySQL函数
    unittest断言 & 数据驱动
    PLSQL
  • 原文地址:https://www.cnblogs.com/codestack/p/12552137.html
Copyright © 2011-2022 走看看