c++ - QMetaObject 上的 lua_newuserdata 位置新增

标签 c++ qt qmetaobject

我正在尝试将 Lua 与 Qt 的 QMetaObject 系统集成。我有一个派生自 QObject 的类,我使用 QObject::staticMetaObject 根据类名将其绑定(bind)到 Lua。

main.h:

#ifndef MAIN_H
#define MAIN_H

class Test : public QObject
{
    Q_OBJECT
public:
    Q_INVOKABLE Test(QObject *parent = 0) : QObject(parent){}

    ~Test(){}
};

Q_DECLARE_METATYPE(Test*)

#endif

main.cpp

#include <QCoreApplication>
#include <QDebug>

#include "main.h"
#include "lua_src/lua.hpp" //Lua include

int CreateUserData(lua_State *L)
{
    const QMetaObject *metaObject = (const QMetaObject*)lua_touserdata(L, lua_upvalueindex(1));

    //PROBLEM AREA
    int typeId = QMetaType::type(metaObject->className());
    if(typeId != QMetaType::UnknownType)//typeId is always unknown
    {
        QMetaType meta(typeId);
        void *ptr = lua_newuserdata(L, meta.sizeOf());
        meta.construct(ptr);
    }
    //PROBLEM AREA

    lua_newtable(L);
    lua_setuservalue(L, 1);

    return 1;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString luaScript("local test = Test.new()");
    lua_State *L = luaL_newstate();

    //bind Test class to lua
    lua_newtable(L);
    lua_pushvalue(L, -1);
    lua_setglobal(L, "Test");

    lua_pushvalue(L, -1);
    lua_pushlightuserdata(L, (void*)&Test::staticMetaObject);
    lua_pushcclosure(L, CreateUserData, 1);
    lua_setfield(L, -2, "new");

    //start script
    luaL_dostring(L, luaScript.toStdString().c_str());
    lua_close(L);
}

问题在于lua将为用户数据分配内存,但不会构造它所代表的对象。所有文档都说使用placement new在lua用户数据的ptr处构造对象,但是QMetaObject不允许开箱即用的placement new。

我包含了来自 ixSci 的有关使用 QMetaTypeptr 构造对象的建议。但是,typeId 总是返回未知。

最佳答案

看起来您需要的内容可以在 QMetaType 中找到类。

因此,要获得您所要求的内容,您需要这样的东西(未经测试!):

int typeId = QMetaType::type(metaObject->className());
if (typeId != QMetaType::UnknownType)
{
    QMetaType meta(typeId);
    meta.construct(ptr, objectToCopy);
}

关于c++ - QMetaObject 上的 lua_newuserdata 位置新增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52091746/

相关文章:

c - 我在哪里可以获得命令行参数?

c++ - 来自 QMetaProperty 的类名

c++,对 ifstream 使用 get 和 >>

C++ 在列表<word>中查找一个句子

c++ - 使用 MYSQL 服务器 (mingw32-make) 为 QT 构建驱动程序时出错

c++ - QMetaObject 调用重载运算符

c++ - QT4 如何使用静态字段?

c++ - 使用c++和cygwin sshd服务的黑色截图

qt - 使用 OpenGL 将图像渲染到子类 QDeclarativeItem