Casting from void * to int
Normally I''d look this up myself, but I haven''t had much luck with Google since this problem is difficult to summarize with keywords.
I am building a dictionary class which is essentially a std::map with a string for the key and a custom class for the value. The custom class is an object that is capable of storing strings, ints, doubles, etc. using a void * which points to a block of memory. The intent is to be able to store settings in their native type and then cast them as needed. I have two questions.
First, is this a braindead way of doing this? Would it make more sense to just convert the data into a string when I store it and then convert it back when it''s requested. This is what I normally see, but it seems like a terrible waste of space (and CPU cycles). This probably isn''t a big deal in my case, but I don''t want to limit myself down the road.
If it makes sense to do what I''m attempting, how do I refernce the void * as an integer (see GetIntValue() function). What I''m doing compiles, but it gives me a nasty warning: pointer truncation from ''void **__w64 '' to ''int''.
void * m_data;
void DictionaryItem::SetValue ( int value )
{
m_dataSize = sizeof ( int );
m_data = malloc ( m_dataSize );
memcpy ( m_data, &value, m_dataSize );
}
int DictionaryItem::GetIntValue ( void )
{
return (int) &m_data;
}
bpopp (bpopp.net)
Look up the "any" class in Boost. It may be just what the doctor ordered.
The warning is warning you about potential problems with this code on a 64-bit architecture. Given how you''re using it, it''s probably okay.
How appropriate. You fight like a cow.
The warning is warning you about potential problems with this code on a 64-bit architecture. Given how you''re using it, it''s probably okay.
How appropriate. You fight like a cow.
If you simply must store those pointers as integers, at least use size_t . instead of int ; if I'm not mistaken, the former will always be the same size as the size of a pointer. Perhaps a better alternative would be to store some arbitrarily-typed pointer, such as char* . To access it, then, just cast the pointer.
[edited by - merlin9x9 on October 7, 2003 4:23:40 AM]
[edited by - merlin9x9 on October 7, 2003 4:23:40 AM]
You''ve mixed up dereferencing and address of operators.
Use this snippet of code, if m_Data is a * of any type:
return *(int*) m_Data;
In words, cast the pointer to an int* and then dereference it.
Use this snippet of code, if m_Data is a * of any type:
return *(int*) m_Data;
In words, cast the pointer to an int* and then dereference it.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement