2

我是 C 新手,正在尝试一些宏语句。我有这样的一行:

#define write_data(src, TYPE, VALUE ) (write_implement(src, sizeof(TYPE), &(VALUE)))

在以后的功能中,我想用它memcpy来复制VALUE另一个内存区域。像这样:

void write_implement (void* src, int size_of_type, void* value)
{
    //whatever, just making the destination address from the source address
    void* dest = src + 4096;
    memcpy(dest, value, size_of_type);
}

传入的 VALUE 可以是任何类型的数据。这就是为什么我使用 void* 来指向它并使用 memcpy 来复制字节大小的数量。

但它当然不起作用:)

这就是我调用函数的方式:

write_data(addr, int, i*3); // i is a whatever integer variable

GCC 给了我这个:

错误:需要左值作为一元“&” 操作数

有谁知道如何找到传递给宏的变量的地址以允许我使用该地址进行复制?

可以更改宏的后半部分(“write_implement”和参数,但不能更改“write_data”参数)。并且实现部分也可以自由更改。

4

3 回答 3

5

如果你的编译器支持 C99 复合文字,你可以这样做:

#define write_data(src, TYPE, VALUE) write_implement(src, sizeof(TYPE), &(TYPE){ VALUE })
于 2010-11-16T02:22:10.317 回答
1

这个怎么样:

#define write_data(src, TYPE, VALUE ) { \
        TYPE xxxx##__LINE__ = (VALUE); \
        write_implement(src, sizeof(TYPE), &(xxxx##__LINE__)); \
    }

在传递它的地址之前,它使用一个有点“随机”的变量来存储值。

于 2010-11-16T02:19:17.917 回答
0

当您展开宏时,您会得到第三个参数&(i * 3),这是没有意义的。您可以获取变量的地址,但不能获取匿名表达式结果的地址。

如果你想在 using 中传递一个值void*来保存类型,那么你最好有一个名为的实际变量来保存它。

int i = 5;
int j = i * 3;
write_data(addr, int, j);

不过,我得说,对我来说直接调用函数更干净:

write_implementation(addr, sizeof(int), &j);

可以做一些 C 魔法来使宏调用看起来像你想要的那样,尽管我不建议这样做。

#define write_data(src,type,value) \
    {type t = (value); write_implementation(src, sizeof(type), &t);}

write_data(addr, int, i*3);

而且,顺便说一句,C++ 模板还允许您以您想要的方式使用表达式的结果,并且更漂亮(关键是 const ref)。

template <typename T>
write_impl(T& dest, const T& src)
{
    memcpy(&dest, &src, sizeof(T));
}

// 'int' is the default type of 5*3
int intResult;
write_impl(intResult, 5*3);

// 'double' is the default type of 5.1*4.7
double doubleResult;
write_impl(doubleResult, 5.1*4.7);

// otherwise, have to cast
long longResult
write_impl(longResult, (long)5*3);
于 2010-11-16T02:18:41.317 回答