我正在尝试将 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 的有关使用 QMetaType
在 ptr
构造对象的建议。但是,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/