Casting from pointer types to non-pointer types


I am interfacing with a third party API (written in C, if that matters) that has an "event handler" function with the following definition: void event_handler(int event_code, unsigned long user_data); The function takes an event code along with the user ...
Posted On: Monday 26th of November 2012 12:50:07 AM Total Views:  375
View Complete with Replies

RELATED TOPICS OF C Language PROGRAMMING LANGUAGE




casting template using const_cast

I have a template class like below. template class XYZ { } const XYZ abc; //Instance of the class How do remove the constantness of abc using const_cast. I mean, I want the syntax for that. Something like const_cast abc gives compiler error.
VIEWS ON THIS POST

361

Posted on:

Sunday 4th November 2012
View Replies!

C++ casting

, Could someone please explain why the (GCC, ancient 2.95.3 version) compiler won't let me static_cast a char* to a unsigned char* or vice versa It also won't accept dynamic_cast for those conversions. The only one it will permit is reinterpret_cast. BTW, yes I know that pointer casts are 'evil', but here's a for- example: ostream::write for some reason expects a const char* and a streamsize parameter, rather than the rather more logical const void* and a size_t. Many of my applications are mucking around with raw binary data either in vector or sometimes in raw unsigned char[], so when I come to write the data out to a file, I have to cast it to a char*. Here's a simple example of the problem: void uc_func(unsigned char *x) {} void c_func(char *x){} int main() { unsigned char uc[10]; char c[10]; uc_func(uc); uc_func(static_cast(c)); c_func(static_cast(uc)); c_func(c); } --------------------------------- g++ -g -o x x.cc x.cc: In function `int main()': x.cc:17: static_cast from `char *' to `unsigned char *' x.cc:19: static_cast from `unsigned char *' to `char *' make: *** [xx] Error 1 g++ -g -o x x.cc xx.cc: In function `int main()': xx.cc:17: cannot dynamic_cast `c' (of type `char[10]') to type `unsigned char *' xx.cc:19: cannot dynamic_cast `uc' (of type `unsigned char[10]') to type `char *' make: *** [xx] Error 1
VIEWS ON THIS POST

178

Posted on:

Monday 5th November 2012
View Replies!

implicit casting operators and template arguments

Hi , Given the following code that just defines a dummy class "my_class" and a dummy wrapper "my_wrapper" with a main program : #include template< typename _Tag > class my_wrapper { public: my_wrapper( _Tag const &tag ) : _M_tag(tag) { } private: _Tag const &_M_tag; }; class my_class { public: operator my_wrapper ( ) { return my_wrapper(*this); } }; int main( int argc, char **argv ) { my_class instance; my_function(instance); return 0; } Now during compilation, and only given the above code, of course, the compiler is going to complain that there is no match for the "my_function" call with the "my_class" argument. If I provide the following function implementation : void function( my_wrapper const &arg ) { std::cout void my_function( wrapper const &arg ) { std::cout
VIEWS ON THIS POST

205

Posted on:

Monday 5th November 2012
View Replies!

virtual functions and dynamic casting

Christopher Pisz wrote: > My problem is my derived class is getting called twice instead of the > base and then the derived. I thought this was the purpose for > virtuals and dynamic casting :/ > I want my base class to have its method called and then the derived > class have its method called. What am I not understanding > > Int the following code, my Event Tester class is getting called twice > for keyboard events when I step through the debugger: > //------------------------------------------------------------------------------------------ > [..badly formatted, incomplete, non-compilable, code removed..] You couldn't have posted in worse shape, even if you tried, probably. I couldn't make heads or tails of the code, I am sorry. Why do you use 'dynamic_cast' to the same type from 'this' Anyway, if you think you're having a language problem (which I am not sure you do, however), remove unnecessary code and make sure you have read and follow the recommendations in FAQ 5.8. Most likely you have some kind of logic problem, but with the code you posted it was not possible to assertain without spending too much time trying to get it back in shape. V -- Please remove capital 'A's when replying by e-mail I do not respond to top-posted replies, please don't ask , Hi! Christopher Pisz schrieb: [snipped a lot of lines] Pleas reduce the size of your posts by deleting lines you are not responding to. > I guess I am going to have to move the entire input mechanism away from the > appplication class. Perhaps into the event manager itself. As suggested by Victor you can move these functionalities into separate classes and use them: class KeyboardState : public EventHandler { private: bool pressedKeys[105]; //or whatever state you need protected: virtual int processEvent(Event* event) { //update keyboard state } }; class GFXApplication { private: KeyboardState keyboardTracker; public: GFXApplication { EventManager::GetInstance()-> RegisterHandler( &keyboardTracker, EVENT_KEYBOARD ); } }; and so on I hope you get the idea. HTH, Frank
VIEWS ON THIS POST

175

Posted on:

Monday 5th November 2012
View Replies!

help for casting

I have one specific purpose container, where it stores struct elem in contiguous memory as, elem* buffer_; the struct elem is struct elem{ size_type index; value_type value; key_type key; }; where types are of usual meaning. i am interested to have one operator value_type& operator[](size_type i), rather than the usual elem& operator[](size_type i); can anyone give a direction how i can cast buffer_[i] to value_type in portable way i.e irrespective of alignments etc. or if i make value_type value as the first in order, will it work
VIEWS ON THIS POST

214

Posted on:

Wednesday 7th November 2012
View Replies!

Safely casting pointer types, purpose of static_cast, etc.

There have been some recent threads about casting pointers to and from void* that have me rethinking some of my usual practices. I have a couple of questions. 1. What is the purpose of C++'s static_cast In other words, is there any real difference between statements like (with non-pointer types): double a = 3.4; int b = (int)a; //
VIEWS ON THIS POST

192

Posted on:

Wednesday 7th November 2012
View Replies!

c++ casting issues

I have a few questions regarding casting in C++. let's take as an example: class A { virtual foo(); }; class B { virtual bar(); }; class C: public A, public B { }; Is it ok to convert a Derived Class instance to a void * and back to a base class For e.g. is it ok to perform the following sequence of steps C* c = new C(); void* p = static_cast(c); B* b = static_cast(p); If not, what is the proper sequence of steps needed to convert a derived instance to a void * and then back to a base class Also, is it ok to compare pointers of a derived class and a base class for equality i.e is the following function guaranteed to work bool IsEqual(B* b, C* c) { return (b == c); }
VIEWS ON THIS POST

164

Posted on:

Wednesday 7th November 2012
View Replies!

lack of implicit casting to T* and boost::shared_ptr::get()

Does anyone know the reasons for the lack of an implicit casting operator in any greater depth than: A. Automatic conversion is believed to be too error prone. (from the FAQ at the bottom of: http://www.boost.org/libs/smart_ptr/shared_ptr.htm) Can anyone say specifically what about the implicit conversion would be dangerous I can think of a few things that would require care about usage of smart pointers with implicit conversions, but nothing that I would consider 'error-prone'. In any language, there are implications and C++ certainly has its fair share of other implicit behaviors.
VIEWS ON THIS POST

193

Posted on:

Wednesday 7th November 2012
View Replies!

Type-punning / casting problem

Dear Experts, I need a function that takes a float, swaps its endianness (htonl) in place, and returns a char* pointer to its first byte. This is one of a family of functions that prepare different data types for passing to another process. I have got confused by the rules about what won't work, what will work, and what might work, when casting. Specifically, I have an implementation that works until I remove my debugging, at which point the compiler seems to decide that it can optimise away the writes to the bytes other than the first, or something like that. Here it is: template inline const char* encode_arg(T& t); // linker error if you try to // encode a type for which there // is no implementation // This one works: template inline const char* encode_pq_arg(int& i) { i = htonl(i); return reinterpret_cast(&i); } // This one doesn't: template inline const char* encode_arg(float& f) { uint32_t* ptr = reinterpret_cast(&f); *ptr = htonl(*ptr); const char* cptr = reinterpret_cast(ptr); return cptr; } When I dump cptr[0] to cptr[3] before the return, it works. Without the debug, it fails; it's obviously hard to see what ends up in the result in that case, but it looks undefined. So, is there some tweak that will make this work, and be certain to work Am I better off using a union, or is that even less defined Does anyone know what the rules actually are Many
VIEWS ON THIS POST

178

Posted on:

Wednesday 7th November 2012
View Replies!

Aliasing, casting and undefined behaviour

Consider a very simple implementation of a matrix class. The class has the option of storing data as row major, or column major, so transposes can be done efficiently by type casting: class RowMajor{}; class ColMajor{}; template struct Matrix: public Container { double& operator()(int row, int col) { return Container::data[row * cols + col]; } Matrix& T() { return static_cast(static_cast(*this)); } }; template struct Matrix: public Container { double& operator()(int row, int col) { return Container::data[row + rows * col]; } Matrix& T() { return static_cast( static_cast(*this)); } }; In this case, a good compiler will optimize away calls to T(), making the transpose operation zero cost. My guess is that the code is technically undefined behaviour (though I'd be suprised if there was an implementation on which it didn't work). Is this the case and if so, is there a portable, well defined way of achieving the free transpose The different matrix types will never have extra data members, they simply interpret the existing data differently. -Ed -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
VIEWS ON THIS POST

146

Posted on:

Wednesday 7th November 2012
View Replies!

type casting inside a templated

Hi all, I am a newbie to C++, here is problem that really gave me a hard time: template class A: B { bool foo(.....) { ........... info.psz = (how do i do cast here ) s.str(); ....................... } } info.psz maybe LPCSTR or LPCWSTR during compile time, the s.str() return unsigned short *. how could I do a cast to satisfy both data type on left side I am using Visual Studio 2005.
VIEWS ON THIS POST

275

Posted on:

Wednesday 7th November 2012
View Replies!

conditional pointer casting

Lets say i pass a structure X to a function which contains a datatype identifier and a void pointer to data itself. Structure definition looks like this: struct CMLD{ int type; unsigned int dims; unsigned int *size; void *data; }; Now, based on the value of X.type i want to declare a certain type of a pointer, call it Array and set it equal to the void pointer stored in X.data. Now. how would i do that Does C suppert conditional declaration, that is: if(X.type==1){ char *Array; } if(X.type ==2){ int *array; } etc. array=X.data; Note, this code would be in a function which may be called multiple times with arguments of diffeent type. By the way i am using C, not C++.
VIEWS ON THIS POST

157

Posted on:

Wednesday 7th November 2012
View Replies!

OOP question: Is upcasting ok in this situation?

If I'm not mistaken, general OOP wisdom says that upcasting should usually be avoided if possible. I have a situation, however, where I can't think of a better way than upcasting for this specific solution. I was wondering if there ...
VIEWS ON THIS POST

158

Posted on:

Saturday 10th November 2012
View Replies!

casting from std::vector

any idea how we can cast from std::vector types. e.g.. i am using the win32 API RegQueryValueEx(). the out buffer it takes should be LPBYTE. i used the code as shown, TCHAR * buf = new TCHAR[2]; RegQueryValueEx(................ (BYTE*)buf)); now ...
VIEWS ON THIS POST

143

Posted on:

Saturday 10th November 2012
View Replies!

[C++0x] unique_ptr type casting helpers

Is there any reason why there isn't any type cast helpers for unique_ptr along the lines of shared_ptr's static_pointer_cast, dynamic_pointer_cast,... something like: template unique_ptr static_pointer_cast(unique_ptr &&ptr) { return unique_ptr(static_cast(ptr.release())); } template ...
VIEWS ON THIS POST

219

Posted on:

Sunday 11th November 2012
View Replies!

upcasting in vector

, I have the following code. #include #include class Foo { public: Foo(){} virtual void print() const { std::cout << "foo" << std::endl;} }; class Boo ublic Foo { public: Boo():Foo(){} virtual void print() const { std::cout << ...
VIEWS ON THIS POST

150

Posted on:

Sunday 11th November 2012
View Replies!

casting to a derived class

I need to make software engineering decision to do with using a derived data type in a container class. So for example, if I have an Edge class, and I want to make a Edge object which contains two NumberVertices ...
VIEWS ON THIS POST

144

Posted on:

Monday 12th November 2012
View Replies!

casting struct to byte *

Hi! I have a byte * (with ample space), and I want to be able to take some byte at start+currentbyte and cast it to a structure type ( and the opposite of taking the bytes of a struct and ...
VIEWS ON THIS POST

123

Posted on:

Monday 19th November 2012
View Replies!

Typecasting goes the wrong way

Hi everybody, I'm trying to build an test-app to check out typecasting. I want to typecast from a bunch of u_chars (unsigned chars) to an structure i created. Here's the code: //////////////////////////////////////////////////////////////////////////////////// #include using namespace std; typedef unsigned char ...
VIEWS ON THIS POST

121

Posted on:

Monday 26th November 2012
View Replies!

some casting questions

, It seems both static_cast and dynamic_cast can cast a base class pointer/reference to a derived class pointer/reference. If so, is there any difference between them In addition, if I have a derived class object and then upcast it to ...
VIEWS ON THIS POST

127

Posted on:

Monday 26th November 2012
View Replies!