lua - 如何在winhttp回调函数中获取lua_State(WINHTTP_STATUS_CALLBACK)?

时间:2015-09-26 18:30:30

标签: c asynchronous lua winhttp

我已经成功实现了同步方式,但是如何以异步方式完成呢?

因为没有办法为winhttp回调添加参数。

WINHTTP_STATUS_CALLBACK theCallback =
    WinHttpSetStatusCallback
    (
    hSession,
    (WINHTTP_STATUS_CALLBACK)HttpCallback,
    WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS,
    NULL
    );

我尝试将lua_State保存为变量并在HttpCallback中使用它,但它会导致访问冲突。

这是我的代码:(不是完整代码)

C

static int callback_reference = 0;
static lua_State *Ltemp;
static int lua_registerCallback(lua_State *L) 
{
    callback_reference = luaL_ref(L, LUA_REGISTRYINDEX);
    return 0;
}
void call_callback(lua_State* L) 
{
    lua_rawgeti(L, LUA_REGISTRYINDEX, callback_reference);
    lua_pushstring(L, buf);
    if (0 != lua_pcall(L, 1, 0, 0)) {
       printf("Failed to call the callback!\n %s\n", lua_tostring(L, -1));
       return;
    }
}
void CALLBACK HttpCallback(HINTERNET hInternet, DWORD * dwContext, DWORD  dwInternetStatus, void * lpvStatusInformation, DWORD dwStatusInformationLength)
{
    //when done
    call_callback(Ltemp);
}
static int doHttp(lua_State *L)
{
    Ltemp = L;
    //init winhttp code here
}

LUA

function callback( result )
    print("ok")
    print(result)
end
lua_registerCallback(callback)
doHttp("http://stackoverflow.com/")

修改 我也尝试过WinHttpSetOption和WinHttpQueryOption,但没有运气。我做错了什么?

//save L
bool result = WinHttpSetOption(
    hRequest,
    WINHTTP_OPTION_CONTEXT_VALUE,
    &L,
    sizeof(struct lua_State *)
    );

//get L, but I think the L is broken here
lua_State* L;
bool result = WinHttpQueryOption(
            hInternet,
            WINHTTP_OPTION_CONTEXT_VALUE,
            &L,
            sizeof(struct lua_State *)
            );

0 个答案:

没有答案