C函数指针参数打印问题

时间:2012-12-18 20:58:23

标签: c++ c function-pointers

我有以下代码:

struct cache_t *                /* pointer to cache created */
cache_create(char *name,        /* name of the cache */
             int nsets,         /* total number of sets in cache */
             int bsize,         /* block (line) size of cache */
             int balloc,        /* allocate data space for blocks? */
             int usize,         /* size of user data to alloc w/blks */
             int assoc,         /* associativity of cache */
             enum cache_policy policy,  /* replacement policy w/in sets */
             /* block access function, see description w/in struct cache def */
             unsigned int (*blk_access_fn) (enum mem_cmd cmd,
                                            md_addr_t baddr, int bsize,
                                            struct cache_blk_t * blk,
                                            tick_t now,
                                            int context_id),
             unsigned int hit_latency)
{                               /* latency in cycles for a hit */
    struct cache_t *cp;
    struct cache_blk_t *blk;
    int i, j, bindex;
----
----
---

  cp->blk_access_fn = blk_access_fn;

----
---

我想打印context_id和baddr。我该怎么做? 我尝试了类型转换和一切,但它一直给我错误: 符号“context_id”在当前上下文中无效。 帮助将得到赞赏。

2 个答案:

答案 0 :(得分:4)

我认为你误解了cache_create函数。它根本没有context_idbaddr个参数。它作为参数的作用是blk_access_fn,它是函数指针。该函数可能由cache_create调用,将这两个变量作为参数。

更好地可视化的方法就像这样:

typedef unsigned int (*blk_access_fn_ptr)(enum mem_cmd cmd, md_addr_t baddr, int bsize, struct cache_blk_t *blk, tick_t now, int context_id);

struct cache_t *            /* pointer to cache created */
cache_create(char *name,        /* name of the cache */
     int nsets,         /* total number of sets in cache */
     int bsize,         /* block (line) size of cache */
     int balloc,        /* allocate data space for blocks? */
     int usize,         /* size of user data to alloc w/blks */
     int assoc,         /* associativity of cache */
     enum cache_policy policy,  /* replacement policy w/in sets */
     /* block access function, see description w/in struct cache def */
     blk_access_fn_ptr blk_access_fn,
     unsigned int hit_latency)  /* latency in cycles for a hit */
{
    ...
}

此代码与您发布的代码的功能相同相同。如您所见,cache_create没有您正在寻找的参数。您必须使用适当的原型作为blk_access_fn参数传递一个函数,它将具有它们。

答案 1 :(得分:0)

如果我正在读这个,你没有传入context_id,你正在接受一个带有context_id参数的fxn指针。您可以在blk_access_fn中访问它们,但不能在cache_create中访问它们。