zoukankan      html  css  js  c++  java
  • tolua 转换 std::shared_ptr

    tolua 转换 std::shared_ptr 

     自从c++11以后std::shared_ptr几乎是比用的东西,经常会遇到类似如下应用

    std::shared_ptr<Tst_ShareTest> createObject(); 

    类似这样的函数在tolua的转换稍稍有些麻烦,今天做了两个实验,下面简单做个总结,由于进度紧张,这里只是做个笔记,没有详细的叙述和严谨的逻辑,如有问题留言。首先在cpp文件中写出要转换的类如下:

    namespace Test {
    
    class Tst_ShareTest
    {
    public:
        void func()
        {
            std::cout << "TEST!!!!!!" << std::endl;
        }
    };
    
    std::shared_ptr<Tst_ShareTest> createObject()
    {
    return std::make_shared<Test::Tst_ShareTest>();
    } }

    1. 第一种思路是利用 std::shared_ptr 中的get()函数获取对象指针,再使用,pkg文件中做如下定义

    namespace std
    {
    class shared_ptr
    {
    TOLUA_TEMPLATE_BIND(T, Test::Tst_ShareTest)
         T *get() const;
    };
    }

    可以看到转换后的代码类似如下

      const std::shared_ptr<Test::Tst_ShareTest>* self = (const std::shared_ptr<Test::Tst_ShareTest>*)  tolua_tousertype(tolua_S,1,0);
    
     {
      Test::Tst_ShareTest* tolua_ret = (Test::Tst_ShareTest*)  self->get();
      tolua_pushusertype(tolua_S,(void*)tolua_ret,"Test::Tst_ShareTest");
     }

    也就是说,转换后的代码会生成一个self对象,用这个对象调用get(),因此我们可以在lua代码中这样调用

    oj = Test.createObject()
    local ojsh = tolua.cast(oj, "std::shared_ptr<Test::Tst_ShareTest>")
    ojp = ojsh:get()
    ojp:func()

    2. 思路二,不想让lua和pkg文件跟std::shared_ptr有太多关联,可以试试用typedef重新定义std::shared_ptr类型。

    typedef std::shared_ptr<Tst_ShareTest> ShareTestPtr;

    在pkg文件中做如下定义:

    class ShareTestPtr
    {
    public:
        Tst_ShareTest *get() const;
    }
    
    Test::ShareTestPtr createObject2();

    在lua中调用方法如下:

    oj2 = Test.createObject2()
    local ojsh2 = tolua.cast(oj2, "Test::ShareTestPtr")
    ojp2 = ojsh2:get()
    ojp2:func()
  • 相关阅读:
    【LeetCode】048. Rotate Image
    【LeetCode】036. Valid Sudoku
    【LeetCode】060. Permutation Sequence
    【LeetCode】001. Two Sum
    【LeetCode】128. Longest Consecutive Sequence
    【LeetCode】081. Search in Rotated Sorted Array II
    【LeetCode】033. Search in Rotated Sorted Array
    顺时针打印矩阵
    矩形覆盖
    二维数组中的查找
  • 原文地址:https://www.cnblogs.com/dangerman/p/6537647.html
Copyright © 2011-2022 走看看