2012-07-06 124 views
1

我哈瓦一類,如:如何通過LUA字符串(二進制)到C++使用tolua ++

class SomeClass 
{ 
    void initFromBuffer(void* buffer,int length); 
    void initFromString(const std::string& str); 
} 

使用tolua ++,有像綁定:

static int SomeClass_initFromBuffer00(lua_State* tolua_S) 
{ 
    SomeClass* self = (SomeClass*) tolua_tousertype(tolua_S,1,0); 
    void* buffer = ((void*) tolua_touserdata(tolua_S,2,0)); 
    int length = ((int) tolua_tonumber(tolua_S,3,0)); 
    self->initFromBuffer(buffer,length); 
} 

和:

static int SomeClass_initFromString00(lua_State* tolua_S) 
{ 

    SomeClass* self = (SomeClass*) tolua_tousertype(tolua_S,1,0); 
    const std::string str = ((const std::string) tolua_tocppstring(tolua_S,2,0)); 
    self->initFromString(str); 
    tolua_pushcppstring(tolua_S,(const char*)str); 
} 

現在,我想要從lua傳遞二進制數據到C++,二進制文件中有'\ 0',所以如果我使用initFromString來傳遞它,二進制數據將被修剪。但是,如果我使用initFromBuffer來傳遞它,我得到壞void ptr'void * buffer =((void *)tolua_touserdata(tolua_S,2,0));指針爲空。

那麼,我怎麼能將二進制字符串從lua傳遞到C++?

回答

1

也許您應該停止使用Tolua糟糕的API並使用純粹的Lua實際上好的 API。 std :: string和Lua字符串都能夠存儲嵌入的空字符。 tolua_tocppstring導致截斷的唯一原因是因爲函數名稱是謊言。它不會將其轉換爲C++字符串;它將其轉換爲C字符串const char*

正確的答案是使用the proper API function

std::string fromLuaStack(lua_State *lua, int stackIx) 
{ 
    size_t len; 
    const char *str = lua_tolstring(lua, stackIx, &len); 
    return std::string(str, len); 
} 

同樣,你可以使用lua_pushlstringstd::string壓入堆棧。

很不幸,Tolua沒有更好的文檔,因爲可能有一個函數可以直接完成這一切。如果有的話,我找不到它。