Skip to main content
gamedev.net
🔒 Locked

Java Vectors in C

Started by omega_001 May 1, 2003 at 3:09 AM 1 replies 650+ views
Original Post
omega_001
omega_001
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.
Enigma
Enigma
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]
omega_001
omega_001
Thanks, that should fit the program nicely.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.