cocos2dx中使用的tolua关于字符串处理的一个问题

在使用cocos2dx的tolua binding的过程中发现一个问题,如果返回或者输入是std::string的时候不允许包含二进制数据,而std::string是允许的,这样一来就造成了一个使用上的不对等,可能会造成一系列的问题,特别是我们需要用std::string来传递一些协议信息的时候。

造成问题的原因是tolua生成的代码对于std::string都没有加入length参数,这样就造成了一旦是二进制数据并且遇到\0就会被截断。修改的办法其实也很简单,只需要修改一下basic.lua脚本,增加如下代码即可


index fac0c7a..4c184c7 100644
--- a/projects/LastMile/Classes/lua/basic.lua
+++ b/projects/LastMile/Classes/lua/basic.lua
@@ -307,7 +307,16 @@ extern "C" {
 
 using namespace cocos2d;
 using namespace cocos2d::extension;
-using namespace CocosDenshion;]])
+using namespace CocosDenshion;
+
+static std::string bt_tocppstring(lua_State* tolua_S, int narg, const char* def) {
+       if(lua_gettop(tolua_S)<abs(narg)) {
+               return "";
+       }
+       size_t length = 0;
+       const char* data = lua_tolstring(tolua_S, narg, &length);
+       return std::string(data, length);
+}]])
 
       replace([[/* Exported function */
 TOLUA_API int  tolua_Cocos2d_open (lua_State* tolua_S);]], [[]])
@@ -323,6 +332,10 @@ TOLUA_API int  tolua_Cocos2d_open (lua_State* tolua_S);]], [[]])
 
       replace([[tolua_usertype(tolua_S,"LUA_FUNCTION");]], [[]])
 
+      replace([[tolua_tocppstring]], [[bt_tocppstring]])
+
+      replace([[tolua_pushcppstring(tolua_S,(const char*)tolua_ret);]], [[lua_pushlstring(tolua_S, tolua_ret.c_str(), tolua_ret.size());]])
+
       replace([[toluafix_pushusertype_ccobject(tolua_S,(void*)tolua_ret]],
         [[int nID = (tolua_ret) ? (int)tolua_ret->m_uID : -1;
     int* pLuaID = (tolua_ret) ? &tolua_ret->m_nLuaID : NULL;


其实就是将里面跟cppstring相关的push和tostring都修改一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值