reinterpret_cast std::function* to and from void*
reinterpret_cast std::function* to and from void*
当我调用从主可执行文件传递的 std::function 时,我在插件中遇到了段错误,方法是将其地址转换为/从void*
. 我可以用几个独立的行重现问题:
#include <iostream>
#include <functional>
int main()
{
using func_t = std::function<const std::string& ()>;
auto hn_getter = func_t{[]() {
return "Hello";
}};
auto ptr = reinterpret_cast<void*>(&hn_getter);
auto getter = reinterpret_cast<func_t*>(ptr);
std::cout << (*getter)() << std::endl; // Bang!
return EXIT_SUCCESS;
}
即使我正在转换为原始类型,它仍然是段错误。 谁能看出我哪里出了问题?
问题的原因与 cast 无关,这是因为函数返回 a const string &
。你需要:
using func_t = std::function<const std::string ()>;
正如评论所暗示的那样,这里的const
是没有用的,只是:
using func_t = std::function<std::string ()>;
相关文章:
- 如何解决"invalid conversion from 'char' to 'const char*'"
- std::time_point from and to std::string
- "No suitable conversion function from 'std::string' to 'const char *' exists"
- dopen():不以 root 身份运行时"failed to map segment from shared object"
- from std::vector to adept::avector
- 为什么我会收到"invalid conversion from 'Queue*/Stack*' to 'int'"错误消息?
- 地图'Cannot convert from _Ty2 to T*'错误
- 查找数组的第一个和最后一个索引,其中 from 和 to 元素的顺序总和最大
- 链接器错误:"cannot move location counter backwards (from 200009f8 to 20000800)"
- 如何递归"print list from tail to head"?
- 为什么选择 g++ 给予者:"error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]"
- 将 2D 数组插入 std::vector 时"cannot convert from 'const GLfloat [12]' to '_Objty'"错误消息
- 返回"Cannot convert from 'std::ofstream {aka std::basic_ofstream<char>}' to bool"错误
- 列表插入"Cannot convert argument from Class<T>* to Class<T> &&"
- reinterpret_cast std::function* to and from void*
- "Cannot convert parameter 1 from double to float"虽然没有更改参数
- 在 iOS 上使用 Aruco 构建 OpenCV 时"Functional-style cast from id to double is not allowed"
- From SMFL to SDL 2.0
- C++常见问题 32.8 "pass an object of a C++ class to/from a C function"问题
- "static_cast<To>(from)"当且仅当"To to{from}",还是不?