473,699 Members | 2,745 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(i nt event_code, unsigned long user_data);

The function takes an event code along with the user data but does not
act on or change the user data.
In my application, I want to pass a pointer as the user data. This
pointer is to an array allocated with new, say, as follows:

char *array = new char[100];

and passed to the event handler as follows:

event_handler(1 , reinterpret_cas t<unsigned long>(array));

My question is if it's safe to cast this to an unsigned long type if I
want to reuse it later? Specifically will doing something like this
cause me any trouble?

void some_function(u nsigned long pointer)
{
char *array = reinterpret_cas t<char*>(pointe r);
/* do stuff with array */
delete [] array;
}

On my machine both sizeof(char*) and sizeof(unsigned long) is 8 so
while this is a pretty ugly solution, at first glance it would seem
safe (at least from overflow).

Jun 6 '07 #1
11 7286
jo***********@g mail.com wrote:
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(i nt event_code, unsigned long user_data);

The function takes an event code along with the user data but does not
act on or change the user data.
In my application, I want to pass a pointer as the user data. This
pointer is to an array allocated with new, say, as follows:

char *array = new char[100];

and passed to the event handler as follows:

event_handler(1 , reinterpret_cas t<unsigned long>(array));

My question is if it's safe to cast this to an unsigned long type if I
want to reuse it later? Specifically will doing something like this
cause me any trouble?
It is safe and well-defined _if_ 'unsigned long' has the same size as
the pointer to which you're casting it.
>
void some_function(u nsigned long pointer)
{
char *array = reinterpret_cas t<char*>(pointe r);
/* do stuff with array */
delete [] array;
}

On my machine both sizeof(char*) and sizeof(unsigned long) is 8 so
while this is a pretty ugly solution, at first glance it would seem
safe (at least from overflow).
It is.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 6 '07 #2
jo***********@g mail.com wrote:
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(i nt event_code, unsigned long user_data);

The function takes an event code along with the user data but does not
act on or change the user data.
In my application, I want to pass a pointer as the user data. This
pointer is to an array allocated with new, say, as follows:

char *array = new char[100];

and passed to the event handler as follows:

event_handler(1 , reinterpret_cas t<unsigned long>(array));

My question is if it's safe to cast this to an unsigned long type if I
want to reuse it later? Specifically will doing something like this
cause me any trouble?

void some_function(u nsigned long pointer)
{
char *array = reinterpret_cas t<char*>(pointe r);
/* do stuff with array */
delete [] array;
}

On my machine both sizeof(char*) and sizeof(unsigned long) is 8 so
while this is a pretty ugly solution, at first glance it would seem
safe (at least from overflow).
I think it would be "generally unsafe", but if your unsigned longs
really are 8 byte, then it will work. Still, an assert() that
sizeof(unsigned long)==sizeof(c har*) somewhere in your code
won't hurt (and it will help others in 20 years' time track
the bug as they port your code to machines using "__further" ,
16-byte pointers :>).

HTH,
- J.
Jun 6 '07 #3
It should be safe. I believe in all current compiler, long and pointer
have same size. Please google "LP64" for more information.

Jun 6 '07 #4
Please quote some context. See my signature.

ga***@yahoo.com wrote:
It should be safe. I believe in all current compiler, long and pointer
have same size. Please google "LP64" for more information.
Not safe.
On a 64bit Windows system, a pointer has 64bit, but long has 32bit like an int.

--
Thomas
http://www.netmeister.org/news/learn2quote.html
Jun 6 '07 #5
ga***@yahoo.com wrote:
It should be safe. I believe in all current compiler, long and pointer
have same size. Please google "LP64" for more information.
Win64 - BAM! - Pointers are 64 bit and longs are 32 bit.
Jun 6 '07 #6
On Jun 6, 12:13 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
jois.de.vi...@g mail.com wrote:
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(i nt event_code, unsigned long user_data);
The function takes an event code along with the user data but does not
act on or change the user data.
In my application, I want to pass a pointer as the user data. This
pointer is to an array allocated with new, say, as follows:
char *array = new char[100];
and passed to the event handler as follows:
event_handler(1 , reinterpret_cas t<unsigned long>(array));
My question is if it's safe to cast this to an unsigned long type if I
want to reuse it later? Specifically will doing something like this
cause me any trouble?

It is safe and well-defined _if_ 'unsigned long' has the same size as
the pointer to which you're casting it.
void some_function(u nsigned long pointer)
{
char *array = reinterpret_cas t<char*>(pointe r);
/* do stuff with array */
delete [] array;
}
On my machine both sizeof(char*) and sizeof(unsigned long) is 8 so
while this is a pretty ugly solution, at first glance it would seem
safe (at least from overflow).

It is.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask


If the sizes differ, will the cast fail with a "loses precision"
error, such as attempting to cast from a pointer to say, an int?

char *array = new char[100];
int ptr_val = reinterpret_cas t<int>(array);

on gcc:
error: cast from 'char*' to 'int' loses precision

not sure if this is true with all compilers ...

Jun 6 '07 #7
jo***********@g mail.com wrote:
[..]
If the sizes differ, will the cast fail with a "loses precision"
error, such as attempting to cast from a pointer to say, an int?
The Standard doesn't say what error message will be displayed. It
is up to the implementation.
char *array = new char[100];
int ptr_val = reinterpret_cas t<int>(array);

on gcc:
error: cast from 'char*' to 'int' loses precision

not sure if this is true with all compilers ...
It is not.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 6 '07 #8
<jo***********@ gmail.comwrote in message
news:11******** **************@ o11g2000prd.goo glegroups.com.. .
>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(i nt event_code, unsigned long user_data);

The function takes an event code along with the user data but does not
act on or change the user data.
In my application, I want to pass a pointer as the user data. This
pointer is to an array allocated with new, say, as follows:

char *array = new char[100];

and passed to the event handler as follows:

event_handler(1 , reinterpret_cas t<unsigned long>(array));

My question is if it's safe to cast this to an unsigned long type if I
want to reuse it later? Specifically will doing something like this
cause me any trouble?

void some_function(u nsigned long pointer)
{
char *array = reinterpret_cas t<char*>(pointe r);
/* do stuff with array */
delete [] array;
}

On my machine both sizeof(char*) and sizeof(unsigned long) is 8 so
while this is a pretty ugly solution, at first glance it would seem
safe (at least from overflow).
Are you sure you are doing what you think you are doing?

array is a char pointer. It contains the address of the 100 characters that
new allocated. Your reinterpret_cas t<unsigned long>( array ) is
reinterpreting this *pointer* to an integer. I suspect you actually wanted
to use the buffer itself to hold the integer. Am I correct?

This program for one run on my system outputs:
4
3288656

Which is it you wanted to use? Notes follow the code.

#include <iostream>

void event_handler(i nt event_code, unsigned long user_data)
{
std::cout << user_data << "\n";
}

int main()
{
char *array = new char[100];

array[0] = 4;
array[1] = 0;
array[2] = 0;
array[3] = 0;
array[4] = 0;
array[5] = 0;
array[6] = 0;
array[7] = 0;

event_handler(1 , *reinterpret_ca st<unsigned long*>( array ));
event_handler(1 , reinterpret_cas t<unsigned long>( array ));

return 0;
}

This can be dangerous on some systems (treating the contents of some other
type as an integer) becasue of byte alignment. On some systems if an
integer is not correctly byte aligned the program can run slower,
malfunction or crash. Generally a integral type needs to be aligned on it's
size. A 4 byte integer on a byte evenly divisible by 4. An 8 byte integer
on a byte evenly divisible by 8, etc... So in that case, if you need to use
the buffer itself as the integer, it may not be safe depending on your
platform.

Notice how I'm passing the *contents* of the buffer as an unsigned long. I
cast the char pointer to an unsigned long pointer, then derefence it (asking
for it's contents).
Jun 7 '07 #9
On Jun 6, 10:28 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
jois.de.vi...@g mail.com wrote:
[..]
If the sizes differ, will the cast fail with a "loses precision"
error, such as attempting to cast from a pointer to say, an int?
The Standard doesn't say what error message will be displayed. It
is up to the implementation.
char *array = new char[100];
int ptr_val = reinterpret_cas t<int>(array);
on gcc:
error: cast from 'char*' to 'int' loses precision
not sure if this is true with all compilers ...
It is not.
Are you sure. According to the standard, "A pointer can be
explicitly converted to any integral type large enough to hold
it." (From the section on reinterpret_cas t.) Converting a
pointer to an integral type which is not large enough to hold it
cannot be done using reinterpret_cas t. A compiler is required
to emit a diagnostic.

According to the C++ standard, the same thing holds for a C
style cast. In C, however, it is undefined behavior, and
C compilers historically have supported it, so that I expect a
lot of C++ compilers will accept it unless you request strict
conformance. Both Sun CC and g++ give an error regardless of
the type of cast, in default mode. Using a C-style cast in C
provokes a warning from gcc, and nothing from Sun cc, however.
This is a point where the two languages differ.

The other direction is fine, however, and there is no problem
using reinterpret_cas t to convert a char to a pointer.

In the case in question, the poster needed a round trip
conversion pointer to integral type back to pointer. This
obviously can only work if the integral type is large enough.
Most of the time, however, it is the reverse that is needed; the
de facto standard "user data" type is void*, and if all you need
is a char... char->void*->char is forbidden by the standard, you
have to use char->void*->intptr_t->char. (And if the system
doesn't have an intptr_t, then you're out of luck.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 7 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
8259
by: Suzanne Vogel | last post by:
** Isn't the 'static_cast' operator the same as traditional type casting? ie, Aren't the following ways of getting b1, b2 the same? // 'Derived' is derived from 'Base' Derived* d = new Derived(); Base* b1 = static_cast<Base*>(d); Base* b2 = (Base*)d; // traditional type casting Such is my understanding from code samples, my own uses, and this: http://www.cplusplus.com/doc/tutorial/tut5-4.html
15
7577
by: Trevor Lango | last post by:
I want to be able to cast away the constness of a private member variable in a member function of a class. I have the private data member declared as follows: const double x; I have an overloaded assignment operator implemented as follows: Point &Point::operator=( const Point *somePoint )
5
3746
by: klaus triendl | last post by:
hi, recently i discovered a memory leak in our code; after some investigation i could reduce it to the following problem: return objects of functions are handled as temporary objects, hence their dtor is called immediately and not at the end of the function. to be able to use return objects (to avoid copying) i often assign them to a const reference. now, casting a const return object from a function to a non-const reference to this...
9
8509
by: Simon | last post by:
Hi All, Is it possible to disallow implicit casting for an operand of a function written in C? i.e. void foo(int a) {..} short b; foo(b) // error without explicit cast
231
23138
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought (perhaps mistakenly) that the purpose of a void pointer was to cast into a legitimate date type. Is this wrong? Why, and what is considered to be correct form?
14
2622
by: mr_semantics | last post by:
I have been reading about the practise of casting values to unsigned char while using the <ctype.h> functions. For example, c = toupper ((unsigned char) c); Now I understand that the standard says this about the <ctype.h> functions: "The header <ctype.h> declares several functions useful for classifying and mapping characters.166) In all cases the argument is an int, the
3
2763
by: Tigger | last post by:
I have an object which could be compared to a DataTable/List which I am trying to genericify. I've spent about a day so far in refactoring and in the process gone through some hoops and hit some dead ends. I'm posting this to get some feedback on wether I'm going in the right direction, and at the same time hopefully save others from going through the process.
5
3002
by: mijobee | last post by:
Hello Everyone, I just wanted to check that I'm using dynamic_cast correctly. I have a hierarchy of objects using pure virtual classes and virtual inheritance to implement interfaces. I ran into a problem using C-style casting to an instance of a derived class from its interface type to a variable of its concrete type. I was confused because I thought C-style casts always compiled even if they wouldn't run correctly at runtime. I...
7
2210
by: Ajeet | last post by:
hi I am having some difficulty in casting using generics. These are the classes. public interface IProvider<PROF> where PROF : IProviderProfile { //Some properties/methods }
19
1947
by: =?Utf-8?B?WWFua2VlIEltcGVyaWFsaXN0IERvZw==?= | last post by:
I'm doing my c# more and more like i used to code c++, meaning i'm casting more often than creating an instance of objects. like : protected void gvOrderDetailsRowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { switch (((Sale)e.Row.DataItem).SzPN) {
0
8686
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9173
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9033
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8882
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5872
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4375
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4627
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3057
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2345
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.