Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中存储对lua函数的引用 我有一个C++中实现的基本事件处理程序。我的应用程序中还有一个嵌入式Lua解释器,需要与事件管理器进行交互。最终的目标是能够有一个事件处理程序,它将在事件被触发时同时执行C++和Lua函数。 我的问题是,我无法想出一个简单的方法来存储对C++代码中的Lua函数的引用。我知道如何从c执行Lua函数(使用Lua\u getglobal和Lua\u pcall),但我更愿意存储对函数本身的引用,这样我就可以将Lua函数直接传递给registerListener_C++_Event Handling_Lua - Fatal编程技术网

在C中存储对lua函数的引用 我有一个C++中实现的基本事件处理程序。我的应用程序中还有一个嵌入式Lua解释器,需要与事件管理器进行交互。最终的目标是能够有一个事件处理程序,它将在事件被触发时同时执行C++和Lua函数。 我的问题是,我无法想出一个简单的方法来存储对C++代码中的Lua函数的引用。我知道如何从c执行Lua函数(使用Lua\u getglobal和Lua\u pcall),但我更愿意存储对函数本身的引用,这样我就可以将Lua函数直接传递给registerListener

在C中存储对lua函数的引用 我有一个C++中实现的基本事件处理程序。我的应用程序中还有一个嵌入式Lua解释器,需要与事件管理器进行交互。最终的目标是能够有一个事件处理程序,它将在事件被触发时同时执行C++和Lua函数。 我的问题是,我无法想出一个简单的方法来存储对C++代码中的Lua函数的引用。我知道如何从c执行Lua函数(使用Lua\u getglobal和Lua\u pcall),但我更愿意存储对函数本身的引用,这样我就可以将Lua函数直接传递给registerListener,c++,event-handling,lua,C++,Event Handling,Lua,注意可以接受假设所有Lua侦听器的用户数据都是NULL 这是我的密码: EventManager.h #include <string> #include <map> #include <vector> using namespace std; typedef void (*fptr)(const void* userdata, va_list args); typedef pair<fptr, void*> Listener; typedef

注意可以接受假设所有Lua侦听器的用户数据都是
NULL

这是我的密码:

EventManager.h

#include <string>
#include <map>
#include <vector>

using namespace std;

typedef void (*fptr)(const void* userdata, va_list args);
typedef pair<fptr, void*> Listener;
typedef map<string, vector<Listener> > CallbackMap;

class EventManager {
private:
    friend ostream& operator<<(ostream& out, const EventManager& r);

    CallbackMap callbacks;
    static EventManager* emInstance;
    EventManager() {
        callbacks = CallbackMap();
    }
    ~EventManager() {
    }
public:
    static EventManager* Instance();
    bool RegisterEvent(string const& name);
    void RegisterListener(string const &event_name, fptr callback,
            void* userdata);
    bool FireEvent(string name, ...);
};

inline ostream& operator<<(ostream& out, const EventManager& em) {
    return out << "EventManager: " << em.callbacks.size() << " registered event"
            << (em.callbacks.size() == 1 ? "" : "s");
}
#包括
#包括
#包括
使用名称空间std;
typedef void(*fptr)(const void*用户数据,va_列表参数);
typedef对侦听器;
typedef映射CallbackMap;
类事件管理器{
私人:

friend ostream&operator我建议将您的函数存储到注册表中,并使用函数
luaL_ref
luaL_unref
提供的引用机制


这些函数使用C<代码> int /CONT>值访问这些值。例如,在C++类成员中存储这样一个整数值很容易。

< P>所有的Lua所拥有的对象都是垃圾收集的。这包括函数。因此,即使您可以获得对Lua函数的引用,Lua仍然拥有它,因此它将服从于每当Lua检测到它不再被引用时,就使用GC

外部代码不能拥有Lua引用。但外部代码可以将该引用存储在Lua代码无法访问(因此无法中断)的地方:Lua注册表

是Lua代码无法(直接)访问的Lua表(位于堆栈伪索引
Lua_REGISTRYINDEX
,因此可以从堆栈中访问)。因此,它是存储所需内容的安全位置。因为它是Lua表,所以可以像任何其他Lua表一样操作它(添加值、键等)

但是,注册表是全局的,如果您使用其他C模块,它们完全有可能开始互相践踏。因此,为每个模块选择一个特定的注册表项并在该注册表项中构建一个表是一个好主意

第一步:初始化C接口代码时,创建一个表并将其粘贴到注册表表中的已知项中。只是一个空表

当Lua代码传递给您一个Lua函数用作回调时,从特殊键加载该表并将Lua函数粘贴在那里。当然,要做到这一点,您需要为每个注册的函数提供一个唯一的键(存储为Lua函数的
void*
数据),您可以稍后使用该键检索该函数

Lua有一个简单的机制来实现这一点:。此函数将使用给定的表在堆栈顶部注册对象。此注册过程保证为每个注册对象返回唯一的整数键(只要您不在系统后面手动修改表).
luaL\u unref
发布一个引用,所有

由于引用是整数键,您可以从
int
转换到
void*
并将其作为数据。我可能会使用显式对象(
malloc
ing
int
),但您可以随意存储它

步骤二:注册Lua函数时,使用
luaL\u ref
将其添加到步骤1中创建的注册表表中。将此函数返回的键存储在注册函数的
void*
参数中

步骤三:当需要调用该函数时,使用存储在
void*
参数中的整数键访问在步骤1中创建的注册表表。这将为您提供该函数,然后您可以使用常用的Lua方法调用该函数


第四步:当您注销Lua函数时,使用
luaL_unref
释放函数(这样可以避免Lua的内存泄漏)。如果您
malloc
ed内存来存储整数键,
在这里释放它。

@Nicolas Bolas提供了很好的说明,但对新手来说太模糊了(包括我自己)。 通过反复试验,我想出了一个有效的例子:

存储 检索
#include <cstdarg>
#include <iostream>
#include <string>

#include "EventManager.h"

using namespace std;

EventManager* EventManager::emInstance = NULL;

EventManager* EventManager::Instance() {
    if (!emInstance) {
        emInstance = new EventManager;
    }

    return emInstance;
}

bool EventManager::RegisterEvent(string const& name) {
    if (!callbacks.count(name)) {
        callbacks[name] = vector<Listener>();
        return true;
    }

    return false;
}

void EventManager::RegisterListener(string const &event_name, fptr callback,
        void* userdata) {
    RegisterEvent(event_name);
    callbacks[event_name].push_back(Listener(callback, userdata));
}

bool EventManager::FireEvent(string name, ...) {
    map<string, vector<Listener> >::iterator event_callbacks =
            callbacks.find(name);
    if (event_callbacks == callbacks.end()) {
        return false;
    }

    for (vector<Listener>::iterator cb =
            event_callbacks->second.begin();
            cb != event_callbacks->second.end(); ++cb) {
        va_list args;
        va_start(args, NULL);
        (*cb->first)(cb->second, args);
        va_end(args);
    }

    return true;
}
#pragma once
#ifndef LUAW_EVENT_H
#define LUAW_EVENT_H

#include "EventManager.h"

extern "C" {

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

void luaw_eventmanager_push(lua_State* L, EventManager* em);
int luaopen_weventmanager(lua_State* L);

}
#endif
#include <assert.h>
#include <stdio.h>

#include <sstream>
#include <iostream>

#include "luaw_eventmanager.h"

using namespace std;

static int
luaw_eventmanager_registerevent(lua_State* L)
{
    int nargs = lua_gettop(L);
    if (nargs != 2) {
        return 0;
    }

    stringstream ss;
    ss << luaL_checkstring(L, 2);

    EventManager::Instance()->RegisterEvent(ss.str());
    return 1;
}

static int
luaw_eventmanager_registerlistener(lua_State* L)
{
    return 1;
}

static int
luaw_eventmanager_fireevent(lua_State* L)
{
    return 1;
}

static int
luaw_eventmanager_tostring(lua_State* L)
{
    stringstream ss;
    ss << *EventManager::Instance();
    lua_pushstring(L, &ss.str()[0]);
    return 1;
}

static const struct luaL_Reg luaw_eventmanager_m [] = {
    {"registerEvent", luaw_eventmanager_registerevent},
    {"registerListener", luaw_eventmanager_registerlistener},
    {"fireEvent", luaw_eventmanager_fireevent},
    {"__tostring", luaw_eventmanager_tostring},
    {NULL, NULL}
};

void 
luaw_eventmanager_push(lua_State* L, EventManager* em)
{
    EventManager** emUserdata = (EventManager**)lua_newuserdata(L, sizeof(EventManager*));
    *emUserdata = em;
    luaL_getmetatable(L, "WEAVE.mEventManager");
    lua_setmetatable(L, -2);
}

int 
luaopen_weventmanager(lua_State* L)
{
    luaL_newmetatable(L, "WEAVE.mEventManager");
    lua_pushvalue(L, -1);
    lua_setfield(L, -2, "__index");
    luaL_register(L, NULL, luaw_eventmanager_m);
    assert(!lua_isnil(L, -1));
    return 1;
}
lua_newtable(L);  // create table for functions
int tab_idx = luaL_ref(L,LUA_REGISTRYINDEX); // store said table in pseudo-registry
lua_rawgeti(L,LUA_REGISTRYINDEX,tab_idx); // retrieve table for functions
lua_getglobal(L, "f"); // retrieve function named "f" to store
int t = luaL_ref(L,-2); // store a function in the function table
// table is two places up the current stack counter
lua_pop(L,1); // we are done with the function table, so pop it
lua_rawgeti(L,LUA_REGISTRYINDEX,tab_idx); // retrieve function table
lua_rawgeti(L,-1,t); // retreive function

//use function
//don't forget to pop returned value and function table from the stack
lua_pop(L,2);