how to convert void* to int

I am using a library which has callback function with void* as a parameter. I need to get int from this void*, below code works fine in c but not in c++

In c:

void *ptr;
int n = (int)ptr;

So in c++ i tried below

int n = atoi(static_cast<const char*>(ptr));

This crashes when i run. Please help me with the right way to convert void* to int in c++
Maybe try reinterpret_cast?

Or keep using a C cast even when C++ code compiled as C++.
using c way gives "error: cast from ‘void*’ to ‘int’ loses precision"
Don't directly cast a pointer to a non-pointer. Pass in a pointer instead, and then dereference that pointer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Example program
#include <iostream>
#include <string>

void my_callback(void* data)
{
    int my_int = *reinterpret_cast<int*>(data);   
    std::cout << "Inside callback, my_int == " << my_int << '\n';
}

void my_library_call(void(callback)(void*))
{
    int data = 42;
    int* p_data = &data;
    callback(p_data);
}

int main()
{
    my_library_call(my_callback);
}
Last edited on
1
2
3
4
5
6
7
8
9
#include <iostream>

int main()
{
    int x = 42;
    void* p = &x; // p points to x
    int y = *static_cast<int*>(p); // dereference pointer
    std::cout << y << '\n';
}

That will obviously crash, if p does not point to an int.
Last edited on
Thanks everyone for the response, Doing below cast works

static_cast<int>(reinterpret_cast<intptr_t>(ptr))
Topic archived. No new replies allowed.