gpt4 book ai didi

c++ - 信号系统调用可以与类的 C++ 静态成员一起使用吗?

转载 作者:太空狗 更新时间:2023-10-29 12:08:27 25 4
gpt4 key购买 nike

*nix 平台是否支持以下内容?

    #include <cstdio>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>

class SignalProcessor
{
public:
static void OnMySignal(int sig_num)
{
printf("Caught %d signal\n", sig_num);
fflush(stdout);

return;
}
};
using namespace std;

int main()
{

signal(SIGINT,SingalProcessor::OnMySignal);
printf("Ouch\n");

pause();

return 0;
}

最佳答案

从技术上讲不,你不能。

您碰巧很幸运,您的编译器使用与“C”函数相同的调用约定。由于未定义 C++ ABI,下一个版本的编译器可以自由使用完全不同的调用约定,这会在编译器没有警告的情况下扰乱您的代码。

参见:http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.2
请参阅本节末尾的注释

Note: static member functions do not require an actual object to be invoked, so pointers-to-static-member-functions are usually type-compatible with regular pointers-to-functions. However, although it probably works on most compilers, it actually would have to be an extern "C" non-member function to be correct, since "C linkage" doesn't only cover things like name mangling, but also calling conventions, which might be different between C and C++.

编辑:
回答 Sasha 的评论:

以线程为例:

#include <iostream>
class Thread
{ public: virtual void run() = 0; };

extern "C" void* startThrerad(void* data)
{
Thread* thread = reinterpret_cast<Thread*>(data);
try
{
thread->run();
}
catch(...)
{ /* Log if required. Don't let thread exit with exception. */ }
return NULL;
}
class MyJob: public Thread
{
public: virtual void run() {std::cout << "HI\n";}
};
int main()
{
MyJob job; // MyJob inherits from Thread
pthread_t th;

// In most situation you do not need to dynamic cast.
// But if you use multiple inheritance then things may get
// interesting, as such best to always use it.
pthread_create(&th,NULL,startThrerad,dynamic_cast<Thread*>(&job));

void* result;
pthread_join(th,&result);
}

关于c++ - 信号系统调用可以与类的 C++ 静态成员一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/971726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com