title: Properly casting a `void*` to an integer in C++
body: <p>I'm dealing with some code that uses an external library in which you can pass values to callbacks via a <code>void*</code> value.</p>
  
  <p>Unfortunately, the previous person working on this code decided to just pass integers to these callbacks by casting an integer to a void pointer (<code>(void*)val</code>).</p>
  
  <p>I'm now working on cleaning up this mess, and I'm trying to determine the "proper" way to cast an integer to/from a <code>void*</code>. Unfortunately, fixing the <em>use</em> of the void pointers is somewhat beyond the scope of the rework I'm able to do here.</p>
  
  <p>Right now, I'm doing two casts to convert from/to a void pointer:</p>
  
  <pre><code>static_cast&lt;int&gt;(reinterpret_cast&lt;intptr_t&gt;(void_p))
  </code></pre>
  
  <p>and </p>
  
  <pre><code>reinterpret_cast&lt;void *&gt;(static_cast&lt;intptr_t&gt;(dat_val))
  </code></pre>
  
  <p>Since I'm on a 64 bit machine, casting directly (<code>(int)void_p</code>) results in the error:</p>
  
  <pre><code>error: cast from 'void*' to 'int' loses precision [-fpermissive]
  </code></pre>
  
  <p>The original implementation <em>did</em> work with <code>-fpermissive</code>, but I'm trying to get away from that for maintainability and bug-related issues, so I'm trying to do this "properly", e.g. c++ casts.</p>
  
  <p>Casting directly to an int (<code>static_cast&lt;int&gt;(void_p)</code>) fails (<code>error: invalid static_cast from type 'void*' to type 'int'</code>). My understanding of <code>reinterpret_cast</code> is that it basically just causes the compiler to treat the address of the value in question as the cast-to data-type without actually emitting any machine code, so casting an <code>int</code> directly to a <code>void*</code> would be a bad idea because the <code>void*</code> is larger then the <code>int</code> (4/8 bytes respectively).</p>
  
  <p>I <em>think</em> using <code>intptr_t</code> is the correct intermediate here, since it's guaranteed to be large enough to contain the integral value of the <code>void*</code>, and once I have an integer value I can then truncate it without causing the compiler to complain.</p>
  
  <p>Is this the correct, or even a sane approach given I'm stuck having to push data through a void pointer?</p>