[英]How to get the address of a variable stated in C Macro?
我是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”參數)。 並且實現部分也可以自由更改。
如果您的編譯器支持C99復合文字,則可以執行以下操作:
#define write_data(src, TYPE, VALUE) write_implement(src, sizeof(TYPE), &(TYPE){ VALUE })
這個怎么樣:
#define write_data(src, TYPE, VALUE ) { \
TYPE xxxx##__LINE__ = (VALUE); \
write_implement(src, sizeof(TYPE), &(xxxx##__LINE__)); \
}
在傳遞其地址之前,它使用一個有點“隨機”的變量來存儲值。
擴展宏時,獲得第三個參數&(i * 3)
,這沒有任何意義。 您可以使用變量的地址,但不能使用匿名表達式結果的地址。
如果要使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.