【发布时间】:2020-06-16 03:02:26
【问题描述】:
我想要一个简单的
something Data() {
return int;
}
或使用 char, long ... w/e
我该怎么办?
我不想返回数字,或者字符串,我想返回数据类型
我尝试过的另一个选项是使用宏
#define Data int
并使用不同的 if 和 else,我可以改用它,但我不能在宏中使用指针,所以这也是一个问题(我需要根据保存在指针中的数字返回数据类型) .
这是我遇到的确切问题,以及到目前为止我所做的:
//Read/write any type from memory
#define MemRead(type, offset) (*((type*)(memory + (offset))))
#define MemSet(type, offset, value) (*((type*)(memory + (offset))) = (value))
//Get the index for type (0 - char, 1 - short, 2 - int ...)
#define TypeIndex (MemRead(unsigned short, 0) % 4)
//#if TypeIndex == 0
//#define TYPE char
//#elif TypeIndex == 1
//#define TYPE short
//#endif
//#define TYPE SOMETHING HERE maybe an if-else ...
//#if TypeIndex == 0 doesn't work, because I can't use * in macros
char *memory = NULL;
void memory_init() {
memory = (char*)ptr;
//Create a list of pointers
int numOfPointers = 1, tsize = size - 3 * IntSize - START;
while (tsize > 64) {
tsize /= 4;
MemSet(int, numOfPointers++ * IntSize - 3, 0);
}
int typeIndex = 0;
if (size < power(2, (sizeof(short) * 8) - 1)) {
typeIndex = 1;
}
else if (size < power(2, (sizeof(int) * 8) - 1)) {
typeIndex = 2;
}
else {
typeIndex = 3;
}
MemSet(unsigned char, 0, numOfPointers * 4 + typeIndex);
MemSet(int, HEADER - IntSize, 0);
int memAvailable = size - HEADER - 3 * IntSize;
setBoundaries(HEADER + IntSize, memAvailable, memAvailable);
MemSet(int, size - IntSize, 0);
//Set beginning pointer
MemSet(int, HEADER - IntSize, HEADER + IntSize);
//Set pointers inside the free block
MemSet(int, HEADER + IntSize, NULL);
MemSet(int, HEADER + 2 * IntSize, HEADER - IntSize);
}
int main() {
char region[500];
memory_init(region, 500);
}
我得到一些内存空间,将第一个 char 设置为一个索引,显示我将使用的数据类型以及列表上有多少指针(每个列表包含不同大小的空闲块),但我无法获得从 TYPE 中获取类型。
我可以在每个函数中使用一个开关来根据内存中的第一个索引处理不同的数据类型,但这很丑陋,也是我寻找更好解决方案的原因。
【问题讨论】:
-
你不能。你为什么要这样做?
-
@SMAEL 函数要么返回对象,要么返回类型为 void。
-
这是XY problem。您需要解决的实际问题是什么?为什么你认为你需要能够返回一个类型?也请花一些时间阅读How to Ask,以及this question checklist。
-
Re“我不想返回数字,也不想返回字符串,我想返回数据类型”,没有这回事。 “数据类型”不是值的类型,所以不能将函数声明为返回“数据类型”类型的值,也不能返回“数据类型”类型的值。
-
无论您认为通过“动态调整大小”整数获得的任何压缩都可能会被您用来跟踪其大小的额外字节所抵消。只需将大小存储为
size_t(无符号整数或长整数)即可。否则,这是一个非常复杂的微优化才能正常工作。