Domanda

unsigned char *check = NULL;
check = (dynamic_cast<unsigned char *>( ns3::NetDevice::GetChannel() ));

This is what I am trying. But the error is:

error: cannot dynamic_cast ‘ns3::NetDevice::GetChannel() const()’ (of type ‘class       ns3::Ptr<ns3::Channel>’) to type ‘unsigned char*’ (target is not pointer or reference to class)

I also tried:

reinterpret_cast

But it doesn't work at all.

È stato utile?

Soluzione

The return type of ns3::NetDevice::GetChannel() is some kind of custom smart pointer; without seeing the definition of that, we can only guess at how you can convert that into a raw pointer.

Perhaps it implements a conversion operator, operator T*(), although that's generally regarded as a bad idea since it makes it unintended conversions too easy to do by accident. In that case, you could do:

void * check = ns3::NetDevice::GetChannel();

Otherwise, perhaps it has a member function to convert to a raw pointer. The standard smart pointers conventionally call this get():

void * check = ns3::NetDevice::GetChannel().get();

If it doesn't offer that, and you really do want to get a raw pointer, then you could dereference it and take a pointer to the dereferenced object (assuming it supports dererencing; otherwise, it's a bit odd to call it a pointer at all):

void * check = &*ns3::NetDevice::GetChannel();

Once you have a void *, you can use static_cast to change it into unsigned char *, if that's what you want. Be careful what you do with it, since messing around with the bytes of an object can easily lead to undefined behaviour.

UPDATE: if ns3::Ptr is the template documented here, then you can get the raw pointer using:

void * check = PeekPointer(ns3::NetDevice::GetChannel());

Altri suggerimenti

It is better to use two static_cast instead of reiterpret_cast. Beacuse the standard does not guarantee that different pointers have same size. But, the standard does guarantee that void* has enough size to fit pointer to any data type (except pointers to functions).

unsigned char *check = NULL;
check = static_cast<unsigned char*>(static_cast<void*>(ns3::NetDevice::GetChannel()));

Your Ptr<Channel> must have overloaded operator, which returns kept pointer:

template<typename T>
class Ptr
{
public:
  operator T*() {return _p;}

private:
  T* _p;
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top