Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C 

How do i get the address of a member function from inside a class?

HI guys, I am trying to get the address of a member function in a class and store it a void pointer within the class. How do i do that?
maybe this could help. I didn't actually read it over but it sounds similar.
http://stackoverflow.com/questions/12988...r-function
[Image: 5Iq5rDJ.gif]

winapi, and winsock programmer

(Mar 16, 2017 08:47 PM)aeiro Wrote:  maybe this could help. I didn't actually read it over but it sounds similar.
http://stackoverflow.com/questions/12988...r-function

Well, thats not exactly the thing i was looking for, but i got my answer from stackexchange.

It seems you can get the address of a member function like this.......


void * a;

a = &A::func();

This gets the address of func from within class A. So yeah, my problem was solved.
Well, you kind of can't.
http://www.dietmar-kuehl.de/mirror/c++-f...l#faq-33.7

What are you trying to do? The general way of getting a member function is by typedefing a member function pointer (or using auto if you're brave enough).

PHP Code

<?php 
#include <iostream>
#include <functional>
#include <string>

class Foo
{
public:
    
typedef void (Foo::*vfuncptr)(void);
    
Foo(int i) : m_i{i}
    { }

    
void print(void)
    {
        
std::cout << m_i << std::endl;
    }

private:
    
int m_i;
};


int main(int argc, char **argv)
{
    
Foo f1(7);
    
Foo f2(3);

    
Foo::vfuncptr ptr = &Foo::print;
    
// converting 'ptr' to a (void*) is a no-no.

    
(f1.*ptr)();
    (
f2.*ptr)();

    return 
0;
} 

There's probably a better way of doing whatever you're trying to do... like, for example, std::function. This would be way better.

PHP Code

<?php 
int main
(int argc, char **argv)
{
    
Foo f1(7);
    
Foo f2(3);

    
std::vector<std::function<void()>> vec;
    
vec.push_back(std::bind(&Foo::print, &f1));
    
vec.push_back(std::bind(&Foo::print, &f2));

    for(
auto func : vec)
    {
        
func();
    }
    return 
0;
} 


or lambdas <3
PHP Code

<?php 
std
::vector<std::function<void()>> vec;
vec.push_back([&f1](){f1.print();});
vec.push_back([&f2](){f2.print();}); 
SRPP Discord Server

I am a professional network/cloud security architect.
My Old Tutorials


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C] by FhackMar 2, 2022 03:52 AM 4 307 Mar 2, 2022 03:52 AM
Last Post: Fhack
[C] by Gliese 667CcAug 28, 2021 11:08 AM 3 192 Aug 28, 2021 11:08 AM
Last Post: Sierra-117
[C] by lockheadApr 22, 2021 07:10 AM 0 147 Apr 22, 2021 07:10 AM
Last Post: lockhead