rttrorg / rttr

C++ Reflection Library
https://www.rttr.org
MIT License
3.11k stars 429 forks source link

get wrong result. #354

Closed LightSun closed 1 year ago

LightSun commented 1 year ago

Hello, rttr is a good project. But I had met some problem. Could you help me ? here is the demo.

include

namespace rttr_med{

struct Color{ float r, g, b, a; };

class ColorMap { public: using K = unsigned char; ColorMap(){};

void put(K k, const Color& c){
    m_map[k] = c;
}
void get(K k, Color& c){
    c = m_map[k];
}

private: std::map<K, Color> m_map; }; }

- ColorMap.cpp

include "ColorMap.h"

include

include

include

include

include

include

include <rttr/registration>

using ColorMap = rttr_med::ColorMap;

RTTR_PLUGINREGISTRATION { rttr::registration::class("ColorMap") .constructor<>() .method("get", &ColorMap::get) .method("put", &ColorMap::put) ; }

- plugin test

include

include

include

include

include

include

include <rttr/type>

using namespace rttr;

ifdef NDEBUG

static string_view library_name("plugin_example");

else

static string_view library_name("plugin_example_d");

endif

include "ColorMap.h"

using Color = rttr_med::Color; using ColorMap = rttr_med::ColorMap;

int main(int argc, char** argv) { setbuf(stdout, NULL); library lib(library_name); // load the actual plugin

if (!lib.load())
{
    std::cerr << lib.get_error_string() << std::endl;
    return -1;
}

{   // scope is important, because we have to free all data before we unload the library

    ColorMap cm;
    {
     std::vector<type> put_types = {type::get<unsigned char>(),
                               type::get<const Color&>()};
    std::vector<type> get_types = {type::get<unsigned char>(),
                               type::get<Color&>()};
        auto t = type::get(cm);
        //auto t = type::get_by_name("ColorMap");
        Color c = {1, 2, 3, 4};
        t.get_method("put", put_types).invoke(cm, 1, c);
        Color c2 = {0, 0, 0, 0};
        t.get_method("get", get_types).invoke(cm, 1, c2);
        printf("c2 = %.1f, %.1f, %.1f, %.1f\n", c2.r, c2.g, c2.b, c2.a);

// expect: c2 = 1, 2, 3, 4, But is 'c2 = 0.0, 0.0, 0.0, 0.0' } } // all data has to be remove before unload the library, otherwise we get UB

if (!lib.unload())
{
    std::cerr << lib.get_error_string() << std::endl;
    return -1;
}

auto t = type::get_by_name("MyPlugin");
if (t.is_valid())
{
    std::cerr << "the type: " << t.get_name() << " should not be valid!";
}

return 0;

}

LightSun commented 1 year ago

fixed