簡體   English   中英

如何將函數指針從 std::function 傳遞給 Linux 克隆?

[英]How can i pass pointer of function from std::function to Linux clone?

我有一個看起來像這樣的課程:

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 函數的參數 + clone()需要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
}

主要思想是使用 MyThread 類,如 std::thread 和 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*參數中解開該std::function並調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM