用相同的数据c++包装/铸造类和结构,以实现外部api

Wrap/Cast class and struct with same data c++ to implement external api

本文关键字:结构 api 外部 实现 数据 c++ 包装      更新时间:2023-10-16

我正试图将外部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的声明可能会潜入您的框架中。这将在糟糕的设计中凸显出来。它需要在设计中努力创建接口和实现的分离,以便它们可以独立更改。