Home Template Function to manipulate memory
Reply: 1

Template Function to manipulate memory

SupaDupa
1#
SupaDupa Published in 2017-12-07 12:28:38Z

I'm modifying the memory of a game, therefor i do something like this:

*(float*)0x89635637 = 10.0f;

Now i want to turn this into a template function which allows me to read and set the memory with only writing the address once, i thought of something like this:

template <typename Variable> Variable GetSetAddress(Variable address, Variable value = NULL)
{
    if (value != NULL)
        *(Variable*)address = value;

    return *(Variable*)address;
}

Now i tried calling it like this:

float value = GetSetAddress<float>(0x89635637, 10.0f);

But it gave me this error:

error C2440: 'type cast' : cannot convert from 'float' to 'float *'

I'm pretty inexperienced with using templates, so i'd be thankful if one of you could point me in the right direction. Thanks in advance!

TartanLlama
2#
TartanLlama Reply to 2017-12-07 12:34:55Z

It doesn't make sense to compare value to NULL, as value in this case is a float. Additionally, the address parameter shouldn't be a Variable, it should be an integral type which can store a pointer value, like std::uintptr_t

template <typename T> T GetSetAddress(std::uintptr_t address, T value)
{
    *(T*)address = value;
    return *(T*)address;
}

It's generally best to avoid c-style casts as well. You could use a reinterpret_cast instead, and simplify the return statement:

template <typename T> T GetSetAddress(std::uintptr_t address, T value)
{
    *reinterpret_cast<T*>(address) = value;
    return value;
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.302491 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO