如何通过名称知道结构的大小 [英] How to know the size of struct by name

查看:50
本文介绍了如何通过名称知道结构的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些问题,请帮助我,谢谢.....
我想通过名称了解某些结构的大小.但是,
我从txt中读取了名称,名称的类型为string.当我使用函数"sizeof()"时,出现了问题.如果字符串为"int",则函数sizeof给出了字符串的大小,而不是字符串的大小. int的大小.
如何使用sizeof通过名称来了解结构的大小?
请帮忙,谢谢....

I have some problems,please help me ,thank you.....
I want to know the size of some structs by their name. But ,
I read the name from a txt and the type of the name is string.When I use the function "sizeof()" ,I have problems.If the string is "int",function sizeof gives the size of the string, not the size of int.
How can I use sizeof to know the size of a struct by their name?
Please help,thank you ....

推荐答案

如果没有其他工作,您将无法做到.
IE.你可以写
Without additional work, you cannot do that.
I.e. you may write
struct Point
{
  int x, y;
};

// ...
size_t s = sizeof(Point);



但是



but

size_t s = SizeOf("Point");


需要C ++中缺少的反射功能.


requires reflection capabilities missing in C++.


使用这个小例子:
Use this little example:
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <tchar.h>

#pragma comment(lib,"user32.lib")

static int scase(const TCHAR* find,const TCHAR* list,TCHAR sep)
{
  unsigned int is,il,done;
  for(done=il=0;list[il];done++)
  {
    for(is=0;(find[is]==list[il])&&(0!=find[is]);is++,il++);
    if((0==list[il]) || (sep==list[il]))
    {
      return 0==find[is]?done:-1;
      if(list[il]) ++il;
    }
    else
    {
      for(++il;list[il]&&(sep!=list[il-1]);il++);
    }
  }
  return -1;
}

size_t sizeof_typename(const TCHAR* typ)
{
  switch(scase(typ,__TEXT("int|short|char|long|__int64|POINT|DWORD|RECT"),'|'))
  {
    case 0return sizeof(int);
    case 1return sizeof(short);
    case 2return sizeof(char);
    case 3return sizeof(long);
    case 4return sizeof(__int64);
    case 5return sizeof(POINT);
    case 6return sizeof(DWORD);
    case 7return sizeof(RECT);
  }
  return 0;
}

int FAR PASCAL _tWinMain(HINSTANCE h,HINSTANCE p,LPTSTR c,int sw)
{
  const TCHAR*  type = __TEXT("__int64");
  size_t        size = sizeof_typename(type);
  TCHAR          msg[256];

  _stprintf_s(msg,sizeof(msg)/sizeof(msg[0]),__TEXT("sizeof(%s) = %i"),type,size);
  MessageBox(0,msg,__TEXT("sizeof_typename"),32);

  return 0;
}


执行此操作的唯一方法是读取文本文件,将结构解析为C/C ++源代码,然后编译并执行结果.您也许可以使用文本编辑器快速完成此操作.
The only way to do this would be to read your text file, parse the structures into C/C++ source code and then compile and execute the result. You may be able to do this quickly with a text editor.


这篇关于如何通过名称知道结构的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆