【发布时间】:2021-12-22 05:40:23
【问题描述】:
我在转换时遇到问题:
std::function <int32_t (std::string &, uint32_t)> 到 typedef int32_t (*callback_c_type) (std::string &, uint32_t(C 函数指针)。
我的完整示例: https://onlinegdb.com/5KI36oPlQ
#include <iostream>
#include <functional>
using namespace std;
typedef int32_t (*callback_c_type) (std::string &, uint32_t);
static int counter = 0;
int32_t my_callback (std::string & index, uint32_t var_id)
{
std::cout << "my_callback => index: '" << index
<< " var_id: '" << var_id
<< "'" << " counter = " << counter << std::endl;
counter++;
return 42;
}
void execute_c_callback(callback_c_type cb)
{
std::cout << "execute_c_callback" << std::endl;
std::string text = "foo";
cb(text, 777);
}
int main ()
{
callback_c_type cb = &my_callback;
execute_c_callback(cb);
std::function <int32_t (std::string &, uint32_t)> cb_2 = cb;
// execute_c_callback((callback_c_type)cb_2);
// PROBLEM: convert std::function<int32_t(std::string&, uint32_t)> -> callback_c_type
return 0;
}
【问题讨论】:
-
投射到
const char*并返回有什么意义?除了问题,它不会增加任何东西。 -
请比“我有问题”更具体。并且不要发布代码链接,发布代码。
-
我认为minimal reproducible example 会有所帮助。但据我所见,我不相信这可以通过演员表来完成。您可能需要某种适配器函数/对象。
-
那是什么图书馆?那个图书馆是谁建的?您确定库将
const char *指针转换为函数指针以调用该指针吗?如果库这样做,请不要使用该库 - 肯定它是一个非常糟糕的库。 ||提供的代码不起作用,因为)>*>(&cb);-&cb是cb指针的地址,而不是它的值。也许你想reinterpret_cast<....>(cb)。不过,这取决于一些假设 - 考虑至少添加static_assert(alignof(const char *) == alignof(std::function<....>)。 -
@MichałHanusek 但是 (a) 为什么 Rust 回调的类型会是
char const*?并且 (b) 你仍然不能将std::function传递给 Rust 库。它需要一个 C 函数指针,而不是指向std::function对象的指针。
标签: c++ function-pointers std-function