void pointers & void function pointers

P

Peter Goddard

Hello,
Is it possible, using casting to promote...

void *Ptr;

To behave like...

void (*FnPtr)(void);

?

i.e. Can the 'void *Ptr' be cast into calling a function once it points to
one?

Cheers

Peter.
 
G

Gordon Burditt

Hello,
Is it possible, using casting to promote...
void *Ptr;
To behave like...
void (*FnPtr)(void);
?
i.e. Can the 'void *Ptr' be cast into calling a function once it points to
one?

There is no guarantee of this. MS-DOS provides an example of having
all possible combinations of 16-bit and 32-bit function pointers
and 16-bit and 32-bit data pointers in the "memory models" small,
compact, medium, and large. If you convert a 32-bit pointer to
16-bits there is substantial risk of losing information you can't
get back.

Gordon L. Burditt
 
E

Eric Sosman

Peter said:
Hello,
Is it possible, using casting to promote...

void *Ptr;

To behave like...

void (*FnPtr)(void);

?

i.e. Can the 'void *Ptr' be cast into calling a function once it points to
one?

No, or "not portably." Function pointers can only point
to functions; data pointers can only point to data. If you
try to coerce a pointer of one class to a pointer of the other,
all bets are off -- on some implementations it will work as
you perhaps hoped, while on others you will be unpleasantly
surprised.

(Usually, people who want to make this conversion have
just filled an array with instructions and want to get the
program to execute them. Quite aside from the difficulties
of converting the pointer, on many machines you will face
other obstacles. For example, a machine that "knows" the
I- and D-spaces are distinct may well have separate cache
mechanisms, and may not bother to synchronize them: you may
wind up executing the garbage that occupied the array before
you stored the instructions, which are still sitting in a
data cache and have not yet been flushed back to memory.
Machines that maintain "permission bits" on regions of memory
may not set the "executable" attribute on any data memory you
can access; you'll get some kind of trap when the CPU tries to
fetch in instruction from a non-executable memory area. And
so on, and so on, into endless machine-dependent territory --
and, perhaps, an appreciation of why the C Standard chose not
to try to enter this particular bramble bush.)
 
P

Peter Goddard

Thanks for the replies. I had a nagging feeling that perhaps this was
possible but not advisable.

Cheers

Peter.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top