2012-04-21 61 views
1

我正在学习一个需要构建线程库的学校任务。 我需要pc来保存给定线程对象的run()函数的地址。 当我尝试一个成员函数指针转换为address_t(这实在是unsigned long int类型)我得到这个错误使用CPP获取成员函数的地址

../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

这里的函数在那里我得到的错误:

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); 
} 

一些澄清:

线程是我写的一个类,目前什么都不做。它作为其“主要”功能作为int run(void)。如我所说,address_ttypedef unsigned long int

任何想法为什么我得到这个错误?谢谢

+0

不要以这种方式使用非静态成员函数。使用非成员函数或静态成员函数。没有类实例,你不能调用成员函数。 – 2012-04-21 12:30:27

回答

4

我不认为你可以做到这一点。

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.

看看this nice faq。如果不能转换为void*,那么你就不能转换为intlong int

1

这并不原因有二:

  1. 函数指针不符合void*(SE UmNyobe的答案)兼容,并且
  2. 为了使用成员函数作为线程条目,您还需要存储this指针。

由于您使用C++你有几种可能性,但:

  1. 使用一个基类thread_base定义虚拟函数作为线程的入口点。
  2. 使用函子作为线程入口点。

无论哪种情况,您都需要将这些信息存储在某个地方,并使用操作系统的线程库调用它。