Archived

This topic is now archived and is closed to further replies.

omega_001

Java Vectors in C

Recommended Posts

omega_001    122
Does anyone know how to ''hide'' data within memory so it can be passed to another program without prior knowledge of what type of data it really is (all it is allowed to know is that its memory, not its structure)? I want to do something similar in C to the Java vector. A Java vector can be assigned any type of data because retrieval is handed by casting the vector element as the data type to be extracted, does anyone know how to do something similar in C? The pseudo code version of this problem is sorta like this: int a=1; int b=0; memory c=NULL; c=a; b=(int)c print b; Output is the integer 1. Thanks K. p.s. I''m fully aware this isn''t strictly a GL question, but it is for a GL project.

Share this post


Link to post
Share on other sites
Enigma    1410
You can either use a void* (a bit nasty) or templating to get what you require.

To use a void* just do:

int a = 1;
int b = 0;
void* c = null;

c = (void*)a;
b = (int)c;

print b;

The alternative (safer) method (if using c++) is to define a templated class:

  
class BaseObject{
public:
virtual ~BaseVector() = 0;
};

BaseObject::~BaseObject(){
// empty virtual destructor;

}

template <typename Datatype>
Class Object{
private:
Datatype data;
public:
Object(Datatype dataItem){
set(dataItem);
}
Datatype get(){
return data;
}
void set(Datatype dataItem){
data = dataItem;
}
};

Which is used like:

int a = 1;
int b = 0;
BaseObject* c = null;

c = new Object<int>(a);
b = dynamic_cast<object<int>*>(c)->get();

print b;


Enigma

Edit: darn < and >!

[edited by - Enigma on May 1, 2003 6:02:33 AM]

Share this post


Link to post
Share on other sites