用相同的数据c++包装/铸造类和结构,以实现外部api
Wrap/Cast class and struct with same data c++ to implement external api
我正试图将外部lib的功能引入框架。外部lib有一个结构,它使用自己的向量结构,但框架有自己的向量类。
如何包装外部lib以使用框架?我需要使用lib的一个功能,但用户不能自己与lib源交互。
// External Lib
namespace Lib
{
struct vec2
{
float x, y;
// Functions
// ....
}
enum ObjectType
{
type0,
type1
};
struct Object
{
/// This constructor sets the body definition default values.
Object()
{
type = type0;
position.set(0.0f, 0.0f);
angle = 0.0f;
active = true;
userData = NULL;
}
ObjectType type;
vec2 position;
float32 angle;
bool active;
void* userData;
};
// The feature I need to use
void CreateObject(const Object* obj);
}
// The Framework
namespace Framework
{
class Vector2
{
f32 x, y;
// Functions ....
}
// In order to use CreateObject from the external lib:
// How to wrap the enum ObjectType to the
// enum class standard here?
// Eg.:
enum class MyObjectType
{
k_type0 = Lib::type0,
k_type1 = Lib::type1
};
// How to wrap struct Object from the external lib
// Eg.:
struct MyObject
{
/// This constructor sets the body definition default values.
MyObject()
{
type = MyObjectType::k_type0;
position = Vector2::k_zero;
angle = 0.0f;
active = true;
userData = nullptr;
}
MyObjectType type;
Vector2 position;
f32 angle;
bool active;
void* userData;
};
// How to create the object?
// I have no idea from here besides manually copy
void MyCreateObject(const MyObject* obj)
{
Lib::Object libObj;
libObj.type = obj.type;
libObj.angle = obj.angle;
Lib::CreateObject(&libObj);
}
}
有很多方法。首先,考虑如何向用户隐藏lib的声明。用户可能只使用您的头文件。所以,不要通过头文件公开它们。仅在cpp文件中使用lib的标头或声明。
然而,有时lib的声明可能会潜入您的框架中。这将在糟糕的设计中凸显出来。它需要在设计中努力创建接口和实现的分离,以便它们可以独立更改。
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 用于访问容器<T>数据成员的正确 API
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- C++为API中定义的结构创建超类
- 声明 Windows API 结构 (DCB) 的对象 - 错误 C4430:缺少类型说明符 - 假定为 int
- 扩展Windows API结构是安全的吗?
- 解密MSDN C API调用和结构,并从VB6调用
- 如何使用节俭C++ API 在 HBase 中存储字节数组(突变结构中的值是文本 ..)
- C++:使用 API 的应用程序体系结构
- 64位Windows API结构对齐导致命名管道上出现“拒绝访问”错误
- 用相同的数据c++包装/铸造类和结构,以实现外部api
- 使用x86/x64 C API的c# AnyCPU库-打包结构,调用和回调
- 初始化派生类中基于 C 的 API 提供的基于 C 的类型定义结构?
- 我想得到一个树结构的完整路径为任何子选择树.有没有可以直接使用的API ?
- 数据结构,用于在挂钩到 API 时跟踪和存储对象
- 我如何从MySQL连接器/ c++获得本机C API连接结构