您可以创建一个不透明的结构包装器而不会造成运行时损失吗?
我有一个可执行文件 A,它动态加载共享库 B。
在 B 中,有一个返回对象的方法。由于多种原因,A 在编译时唯一能知道的有关该对象的信息是它的大小(以字节为单位)。它不知道有多少个字段,甚至不知道它的类型。然而,A 负责保留该句柄。
例如,如果 B 创建的对象的大小是 int(例如,具有 4 字节大小字段的 POD 结构)。
您可以制作这种包装器:
struct ObjectHandle
{
uint64_t handle = 0;
ObjectHandle() {}
ObjectHandle(uint64_t h) : handle(h) {}
operator uint64_t() {return handle;}
};
您现在可以将要表示的对象类型转换为 uint64_t,并且 A 可以保留它,即使不知道它是什么,它所知道的是 ObjectHandle
是一些带有以下内容的数据:一些尺寸。
对于数据不适合 uint64_t 的情况,我需要完成相同的操作。
即我想创建一个具有已知字节大小的对象,其唯一目的是充当相关数据的不透明字节容器。
“为什么不使用指针并将其保留为空”?
间接,这适用于时间关键的系统,使用指针执行此操作会导致缓存未命中,这是一种太大的惩罚。类型转换不应该有运行时损失。
这是可以实现的吗?
I have an executable A that dynamically loads a shared library B.
Within B there is a method that returns an object. For a variety of reasons the only thing that A can know at compile time about this object is its size in bytes. It doesn't know how many fields there are or even its type. However A is responsible of keeping this handle around.
If the size of the object created by B is an int for example (e.g. a POD struct with 4 byte size fields).
You can make this kind of wrapper:
struct ObjectHandle
{
uint64_t handle = 0;
ObjectHandle() {}
ObjectHandle(uint64_t h) : handle(h) {}
operator uint64_t() {return handle;}
};
You can now typecast the object to be represented into a uint64_t and A can keep it around even without knowing what it is, all it knows is that ObjectHandle
is some data with some size.
I need to accomplish the same for cases where the data doesn;t fit into a uint64_t.
i.e. I want to create an object with a known byte size whose only purpose is to act as an opaque byte container for the relevant data.
"Why not pointers and keep it as void"?
Indirection, this is for a time critical system, the cache misses from doing this with pointers is too much a penalty. The type casting should have no runtime penalties.
Is this achievable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论