2012-04-21 27 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. 使用函子作爲線程入口點。

無論哪種情況,您都需要將這些信息存儲在某個地方,並使用操作系統的線程庫調用它。