yotamoo
yotamoo

Reputation: 5452

Getting the address of a member function, using CPP

I am working on a school assignment in which I need to build a thread library. I need pc to hold the address of the given Thread object's run() function. When I try to cast a member function pointer to address_t (which is really unsigned long int) I get this error

../main.cpp: In function ‘void setup(Thread&)’:

../main.cpp:77:22: error: invalid cast from type ‘int (Thread::*)()’ to type ‘address_t {aka unsigned int}’

make: * [main.o] Error 1

Here's the function where I get the error:

void setup(Thread &thread)
{
    address_t sp, pc;

    sp = (address_t)stack1 + STACK_SIZE - sizeof(address_t);
    int (Thread::*temp)() = &Thread::run;
    pc = (address_t) temp; // @@ LINE 77 @@

    sigsetjmp(jbuf[0],1);
    (jbuf[0]->__jmpbuf)[JB_SP] = translate_address(sp);
    (jbuf[0]->__jmpbuf)[JB_PC] = translate_address(pc);
    sigemptyset(&jbuf[0]->__saved_mask);
}

A few clarification:

Thread is a class I wrote, currently doing nothing. It as a int run(void) as its "main" function. address_t, as I said, is typedef unsigned long int

Any ideas as to why I get this error? thanks

Upvotes: 1

Views: 291

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545508

This doesn’t work for two reasons:

  1. function pointers are not compatible with void* (se UmNyobe’s answer), and
  2. in order to use member functions as the thread entry you’d need to store a this pointer as well.

Since you’re using C++ you’ve got a few possibilities though:

  1. Use a base class thread_base defining a virtual function as the thread entry point.
  2. Use a functor as the thread entry point.

In either case you’d need to store this information somewhere and invoke it using the operating system’s thread library.

Upvotes: 1

UmNyobe
UmNyobe

Reputation: 22890

I don't think you can do that.

void pointers are pointers to data, and function pointers point to functions. The language does not require functions and data to be in the same address space, so, by way of example and not limitation, on architectures that have them in different address spaces, the two different pointer types will not be comparable.

Take a look at this nice faq. If you cannot convert to void*, then you cannot convert to int or long int

Upvotes: 4

Related Questions