I need to create an object and return it back as an integer anssalso convert an int to a class/object pointer in a function as a parameter and back again as integer for the result.
What is the best way to do this? Basically my ideal setup will be like this:
1 2 3 4 5
int foo;
foo = CreateObject(); // function declared as MyClass* CreateObject();
DoSomething(foo); //function accepting MyClass* as param
I have seen this mostly used in C wrappers, I understand passing object or class pointers is normal in C as well but I need to pass it an integer for something that I am working on that really requires it to be integer.
An object pointer is not guaranteed to fit into an int, but there is uintptr_t that is the right size to hold a pointer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
class A {
public:
void f() { std::cout << "yo\n"; }
};
void func(uintptr_t u) {
auto a = reinterpret_cast<A*>(u);
a->f();
}
int main() {
A* a = new A;
auto u = reinterpret_cast<uintptr_t>(a);
func(u);
delete a;
}
I have no idea how you could do that but by a reinterpret_cast<>, as dutch suggested; but perhaps this code might give you some hints about alternatives:
An object pointer is not guaranteed to fit into an int
What makes you think that a pointer will fit inside an int in your system? If you're running a 64-bit operating system then chances are excellent that an int is 32 bits and a pointer is 64 bits.
Do you really, truly, absolutely HAVE to pass it as an int? The only reason I can think of is if you're passing it to a function that already exists.
If you're writing the function then figure out how to pass the pointer as a pointer. Maybe it needs to be a void*?