home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / lang / c / 19424 < prev    next >
Encoding:
Text File  |  1993-01-08  |  2.3 KB  |  60 lines

  1. Path: sparky!uunet!inmos!wraxall.inmos.co.uk!elberton!nathan
  2. Newsgroups: comp.lang.c
  3. From: nathan@inmos.co.uk (Nathan Sidwell)
  4. Subject: Re: Is that ansi ?
  5. Message-ID: <1993Jan8.165451.7873@wraxall.inmos.co.uk>
  6. X-Newsreader: TIN [version 1.1 PL8]
  7. References: <mcdonald.28@aries.scs.uiuc.edu>
  8. Date: Fri, 8 Jan 93 16:54:50 GMT
  9. Lines: 49
  10.  
  11. J. D. McDonald (mcdonald@aries.scs.uiuc.edu) wrote:
  12. : In article <1993Jan8.142730.20697@osf.org> daniel@moonshine.osf.org (Daniel Dardailler) writes:
  13. : >A compiler is reporting the following warning:
  14. : >  "void * and function pointers are not convertible to each other"
  15. : >when encountering:
  16. : >       void * p = (void *) func ;   /* func of any kind */
  17.  
  18.  
  19. : I'm afraid it's true, and one of the most serious faults of ANSI C.
  20.  
  21. And a very good reason for it too. As I emailed to Daniel, some systems require
  22. more than an instruction pointer to reference a function. For example an
  23. environment pointer. Now ANSI could have said void * is big enough to 
  24. hold any pointer, but then on such systems, most void pointers would carry
  25. extra unrequired baggage with them.
  26.  
  27. : Function pointers are orthogonal to everything else.  What you can do
  28. : is somehow convert them to an integer type and convert that to 
  29. : void * pointer and then go back. The standard itself does not 
  30. : guarantee that the conversion will get back the right answer however.
  31. : (For those who need a proof, checked with Doug Gwyn, that this can be done:
  32. : enclose the function pointer in a struct, write out the struct to a 
  33. : file using fwrite, then read back in into a char array of the correct size.
  34. : This is guaranteed to work.) Another way is to try and use unions. This
  35. : is not absolutely guaranteed to work.
  36.  
  37. : Doug McDonald
  38.  
  39. Another way, which doesn't require file io is, (unchecked, I may
  40. have got the casting slightly wrong).
  41.  
  42. void (*fptr)(void);
  43. char *cptr;
  44.  
  45. fptr = (void (*)(void))function;
  46. cptr = (char *)&fptr;
  47.  
  48. /* cptr now points to an array sizeof(fptr) of chars which are the function
  49. pointer */
  50.  
  51. Now I'm not 100% sure that you can cast any function pointer to void (*)(void), and
  52. back again without loss, but I can find nothing in ANSI which states this, and
  53. can think of no reason why that might not be so.
  54.  
  55. nathan
  56. --
  57.  
  58. Nathan Sidwell  INMOS UK |                 | nathan@inmos.co.uk       DoD#0390
  59.  
  60.