2011-06-27 252 views
5

void (*)(int)類型的參數與__sighnd64_tC++中的信號處理

類型的參數不兼容

下面是我的簡單代碼:

#include <iostream> 
#include <string> 
#include <signal.h> 
#include <ctype> 
#include <stdlib.h> 
#include <stdio.h> 
typedef struct mystrcut 
{ 

    int a; 
    char *b; 

} mystr; 

void set_string (char **, const char *); 
void my_handler(int s) 
{ 
    printf("Caught signal %d\n",s); 
    exit(1); 

} 

int main() 
{ 
    const std::string str1[] = {"hello1", "hello2"}; 
    char str2[50]; 
    size_t size1 = str1[1].size(); 
    cout << size1; 
    memcpy (str2, str1[1].c_str(), size1); 

    cout << str2; 
    mystr *m = NULL; 
    m = new mystrcut; 
    m->a = 5; 

    set_string(&m->b, "hello"); 

    cout << m->b; 
    delete []m->b; 
// void (*prev_fn)(int); 
    signal (SIGINT,my_handler); 
    return 0; 
} 
void set_string (char **a, const char *b) 
{ 
    *a = new char [strlen(b)+1]; 
    strcpy (*a, b); 
} 

我正在研究openvms。我可以通過某種類型轉換來避免編譯錯誤嗎?我的編譯器需要`__sighnd64_t __64_signal(int,__sighnd64_t);

添加處理程序extern c已經有效。謝謝

+0

這是奇怪,因爲據我所知'__sighnd64_t'被typedef定義爲'無效(*)(INT)'。但是在你的代碼中還有其他的問題......例如'cout'必須是一個未聲明的標識符,因爲你不使用'std ::' –

+0

你可能必須在文件中尋找你的編譯器(哪一個?) ,以確切地看到它對'signal()'參數的期望。 –

+2

對不起,也許愚蠢的問題,但你有編譯問題?在Linux上編譯和工作,在需要的地方添加正確的std ::。 – dave

回答

3

的信號處理是不是C++,但C.此錯誤是有點奇怪......

在這種情況下,儘量使用外部的「C」在你的處理程序(將其定義爲C函數) ,因爲https://stackoverflow.com/users/775806/n-m在評論中表示。來自openvms的現代<signal.h>已經具有外部「C」內部:http://wasd.vsm.com.au/conan/sys$common/syslib/decc$rtldef.tlb?key=SIGNAL&title=Library%20/sys$common/syslib/decc$rtldef.tlb&referer=http%3A/wasd.vsm.com.au/conan/sys$common/syshlp/helplib.hlb

HP docs says只關於C,而不是C++。

Another doc說,信號處理器(捕手)必須在C語言中聲明爲

void func(int signo); 
+3

我不相信你需要將函數聲明爲'extern「C」',以便根據C代碼調用它們。我認爲你只需要通過C代碼中的名稱來引用它。由於指向信號處理程序的指針正在被傳遞,這意味着它不需要被聲明爲「extern」C「'。 – Omnifarious

+0

但添加extern「c」已經工作 – Sam

+1

@Sam:這很有趣。我想知道是否使用的函數調用約定是系統類型的一部分。 – Omnifarious