-
dynamic ptr types
Hi,
I am just wondering if it is at all possible to redefine the type of a pointer at runtime? For example, say I have char *pBuffer, but instead of it pointing to a type char, I now want it to point to a type of short signed *pBuffer. However, I still want to be able to use the same indentifier i.e. pBuffer. I know you can use the reinterpret_cast operator, but that is not permenant, and I don't want to be using that constantly throughout my for loop when subscripting.
Any Ideas?
Thanks, Dene.
-
The closest match to what you want is a pointer to void. That's the generic pointer type in C++ and you can assign any pointer to it. You might have some issues with dereferencing the pointer if you use it in a hardcoded loop though. What exactly are you trying to do? It sounds like your design is off.
-
I am analysing a sine wave which is dependant upon the bits per sample, (which could either be 8 or 16). I was going to do this:
Code:
f(void *pSampleBuffer)
{
bool bPtrType = false;
int iSample1, iSample2;
char *cptrData = (char*)pSampleBuffer;
short signed *iptrData = (short signed *)pSampleBuffer;
if((m_wfWaveFormat.wBitsPerSample / 8 == 2) bPtrType = true;
for(int i = 0; i < bla bla - 1; i++)
{
if(bPtrType)
{
iSample1 = iptrData[i];
iSample2 = iptrData[i + 1];
}
else
{
iSample1 = cptrData[i]
iSample2 = cptrData[i + 1]
}
//then the rest of the code would use the iSample1 and iSample2
}
}
-
You could tuck all of the nasty stuff safely in an object to avoid switching on arbitrary attributes. That would clean up your function a bit:
Code:
class sample_list {
public:
sample_list(void *buffer, int size, bool is_byte);
int next();
bool done();
private:
unsigned char *pbuffer;
int buf_size;
int current;
bool use_byte;
};
sample_list::sample_list(void *buffer, int size, bool is_byte)
: pbuffer(static_cast<unsigned char *>(buffer))
, buf_size(size)
, current(0)
, use_byte(is_byte)
{}
int sample_list::next()
{
int ret;
if (use_byte) {
ret = pbuffer[current];
}
else {
ret = (reinterpret_cast<short int *>(pbuffer))[current];
}
++current;
return ret;
}
bool sample_list::done()
{
return current == buf_size;
}
void f(void *sample_buffer, int size)
{
bool is_byte_sample = m_wfWaveFormat.wBitsPerSample / 8 == 1;
sample_list samples(sample_buffer, size, is_byte_sample);
int sample;
while (!samples.done()) {
sample = samples.next();
// Use sample
}
}
There are several ways to solve this problem, but none of them are really good and elegant at the same time. :(
-
Robc : Thanks very much for that solution, it is very good and encapsulates alot of the lower level stuff.
Cheers.