c++ - 如何将函数的指针从std::function传递给Linux克隆?

标签 c++ linux c++11 lambda std-function

我有一个类,看起来像这样:

class MyThread{
private:
    pid_t pid;
    size_t stack_size;
    char* child_stack;
    void* child_stack_end; 

public:

// --methods--

    MyThread(std::function<int(void*)> const& fun) {
        stack_size = 1024*10;
        child_stack = new char[stack_size];
        child_stack_end = child_stack + stack_size;

        int (*const* ptr)(void*) = fun.target<int(*)(void*)>();

        pid = clone(*ptr, child_stack_end, CLONE_VM | 
        CLONE_FS | CLONE_FILES | CLONE_SIGHAND | SIGCHLD, 0);
    }
}

我想用带有lambda的合并排序函数来测试它(不要创建MyThread类的构造函数,女巫需要使用merge_sort_thread函数的args + clone()的args需要int(*)(void*)函数作为1个参数):
MyThread([first, center](void* arg){
    return merge_sort_thread(first, center);
});

然后我尝试这段代码,它返回SIGSEGV。
我用GDB检查过,变量ptr等于0x0。
我该如何解决?

合并排序功能如下:
template<typename T>
static int merge_sort_thread(T first, T last){ // working with pointers 
   //sorting
}

好吧,主要思想是将带有std::thread的MyThread类与lambda一起使用
std::thread([first, center](){
    return merge_sort_thread(first, center);
});

最佳答案

简而言之,你不能。捕获的lambda与函数指针不兼容,因此您对fun.target<int(*)(void*)>的调用将返回空指针。将其传递给clone会导致段错误。

这就是clone使用void* args参数将(指针)任意数据传递到回调函数的原因:这有效地实现了捕获的作用。如果要将自定义std::function传递给clone,则需要将其包装到带有签名int(void*)的函数中,该函数在内部从其std::function参数解开该void*并对其进行调用。

关于c++ - 如何将函数的指针从std::function传递给Linux克隆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59694350/

相关文章:

c++ - 创建一个非拥有的 shared_ptr?

c++ - 单独更改我的应用程序的字体平滑而不是全局 Windows 字体平滑设置

C#程序Windows与linux时间同步

linux - 覆盖文件时 sed 权限被拒绝

PHP 无法读取文件

c++ - 为什么我可以复制 unique_ptr?

c++ - 什么是静态或常量抛出错误?

c++ - 按下任何 QPushButton 时应用程序范围内的日志记录

c++ - 将 unsigned char * 转换为 FlyCapture2 Image for cvShowImage OpenCV

c++ - boost 时出现段错误( boost :filesystem:exists)