Question

I trying to make a system for storing lua compiled scripts in memory. The problem is that I can not make a "lua_Writer", and the variable bytecode is empty. I using Luajit. Below my code.

typedef struct {
    size_t *len;
    char **data;
} BS_DESCRIP;

int scriptMemoryWriter(lua_State* ls, const void* p, size_t sz, void* ud)
{
    BS_DESCRIP* bd = (BS_DESCRIP*)ud;
    char* newData; = (char*)realloc(*(bd->data), (*(bd->len)) + sz);

    if(newData)
    {
        memcpy(newData + (*(bd->len)), p, sz);
        *(bd->data) = newData;
        *(bd->len) += sz;

    } else {
        free(newData);

        return 1;
    }

    return 0;
}

void HScriptManager::compileToMemory(HScript* script)
{
    char* bytecode = 0L;
    size_t bytecode_len = 0;
    BS_DESCRIP bd = {&bytecode_len, &bytecode};

    int buff_ret = luaL_loadbuffer(m_pLuaState, script->getData().c_str(), script->getBuffSize(), script->getName().c_str());
    int comp_ret = lua_dump(m_pLuaState, scriptMemoryWriter, &bd);

    lua_pop(m_pLuaState, 1);

    std::cout << "bytecode_len: " << bytecode_len << std::endl;
    std::cout << "bytecode: " << bytecode << std::endl;

    std::cout << "buff_ret: " << buff_ret << std::endl;
    std::cout << "comp_ret: " << comp_ret << std::endl;
}

Variable contents bytecode is incomplete. Look

Incomplete

Complete

Note: I did not do this "Writer". Sorry for english...

Was it helpful?

Solution 2

I'm going to assume that char* newData; = (char is a typo in your question because such code would not compile.

I believe the problem is that you are trying to print the bytecode as a string of characters. If you give a std stream (like std::cout) a pointer to a character, the stream will print all the characters, starting at that memory location, up to but not including the first null character it finds after that memory address. Now I have never looked at Lua bytecode but I suspect that Lua bytecode can have null bytes, which would cause the printout to appear incomplete. You were just lucky in your "complete" example, that there were no null bytes.

Since a lot of the bytecodes will be unprintable characters, you might as well print their decimal value instead. Replace std::cout << "bytecode: " << bytecode << std::endl; by:

std::cout << "bytecode: ";
for (int i=0; i<bytecode_len; i++)
    std::cout << int(bytecode[i]) << " ";
std::cout << std::endl;

OTHER TIPS

Line 9: char* newData; = (char*)realloc(*(bd->data), (*(bd->len)) + sz);

Do not put ; after char* newData.

This is correct:

char* newData = (char*)realloc(*(bd->data), (*(bd->len)) + sz);

Although, I am still not sure if it will work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top