Beispiel #1
0
//-------------------------------------------------------------------------------------
int FixedDict::mp_ass_subscript(PyObject* self, PyObject* key, PyObject* value)
{
	wchar_t* PyUnicode_AsWideCharStringRet0 = PyUnicode_AsWideCharString(key, NULL);
	char* dictKeyName = strutil::wchar2char(PyUnicode_AsWideCharStringRet0);
	PyMem_Free(PyUnicode_AsWideCharStringRet0);

	FixedDict* fixedDict = static_cast<FixedDict*>(self);
	if (value == NULL)
	{
		if(!fixedDict->checkDataChanged(dictKeyName, value, true))
		{
			free(dictKeyName);
			return 0;
		}

		return PyDict_DelItem(fixedDict->pyDict_, key);
	}
	
	if(!fixedDict->checkDataChanged(dictKeyName, value))
	{
		free(dictKeyName);
		return 0;
	}

	PyObject* val1 = 
		static_cast<FixedDictType*>(fixedDict->getDataType())->createNewItemFromObj(dictKeyName, value);

	int ret = PyDict_SetItem(fixedDict->pyDict_, key, val1);
	
	// 由于PyDict_SetItem会增加引用因此需要减
	Py_DECREF(val1);

	free(dictKeyName);
	return ret;
}
static PyObject *Rainmeter_RmReadPath(RainmeterObject *self, PyObject *args)
{
	PyObject *option, *defValue;
	PyArg_ParseTuple(args, "UU", &option, &defValue);
	wchar_t *optionStr = PyUnicode_AsWideCharString(option, NULL);
	wchar_t *defValueStr = PyUnicode_AsWideCharString(defValue, NULL);
	LPCWSTR result = RmReadPath(self->rm, optionStr, defValueStr);
	PyMem_Free(defValueStr);
	PyMem_Free(optionStr);
	if (result == NULL)
	{
		Py_INCREF(Py_None);
		return Py_None;
	}
	return PyUnicode_FromWideChar(result, -1);
}
Beispiel #3
0
//-------------------------------------------------------------------------------------
std::string Dbmgr::selectAccountDBInterfaceName(const std::string& name)
{
	std::string dbInterfaceName = "default";

	// 把请求交由脚本处理
	SCOPED_PROFILE(SCRIPTCALL_PROFILE);
	PyObject* pyResult = PyObject_CallMethod(getEntryScript().get(),
		const_cast<char*>("onSelectAccountDBInterface"),
		const_cast<char*>("s"),
		name.c_str());

	if (pyResult != NULL)
	{
		wchar_t* PyUnicode_AsWideCharStringRet0 = PyUnicode_AsWideCharString(pyResult, NULL);
		char* ccattr = strutil::wchar2char(PyUnicode_AsWideCharStringRet0);
		dbInterfaceName = ccattr;
		PyMem_Free(PyUnicode_AsWideCharStringRet0);
		Py_DECREF(pyResult);
		free(ccattr);
	}
	else
	{
		SCRIPT_ERROR_CHECK();
	}

	if (dbInterfaceName == "" || g_kbeSrvConfig.dbInterface(dbInterfaceName) == NULL)
	{
		ERROR_MSG(fmt::format("Dbmgr::selectAccountDBInterfaceName: not found dbInterface({}), accountName={}.\n", dbInterfaceName, name));
		return "default";
	}

	return dbInterfaceName;
}
Beispiel #4
0
//-------------------------------------------------------------------------------------		
PyObject* ClientApp::__py_fireEvent(PyObject* self, PyObject* args)
{
	if(PyTuple_Size(args) < 1)
	{
		PyErr_Format(PyExc_AssertionError, "ClientApp::fireEvent: arg1(eventName) not found!\n");
		PyErr_PrintEx(0);
		return NULL;
	}

	PyObject* pyname = PyTuple_GetItem(args, 0);

	if(!pyname || !PyUnicode_Check(pyname))
	{
		PyErr_Format(PyExc_AssertionError, "ClientApp::fireEvent: arg1(eventName) not found!\n");
		PyErr_PrintEx(0);
		return NULL;
	}

	wchar_t* PyUnicode_AsWideCharStringRet0 = PyUnicode_AsWideCharString(pyname, NULL);
	char* name = strutil::wchar2char(PyUnicode_AsWideCharStringRet0);
	PyMem_Free(PyUnicode_AsWideCharStringRet0);

	EventData_Script eventdata;
	eventdata.name = name;
	free(name);

	if(PyTuple_Size(args) - 1 > 0)
	{
		PyObject* pyitem = PyTuple_GetItem(args, 1);

		PyUnicode_AsWideCharStringRet0 = PyUnicode_AsWideCharString(pyitem, NULL);
		if(PyUnicode_AsWideCharStringRet0 == NULL)
		{
			PyErr_Format(PyExc_AssertionError, "ClientApp::fireEvent(%s): arg2 not is str!\n", eventdata.name.c_str());
			PyErr_PrintEx(0);
			return NULL;
		}

		char* datas = strutil::wchar2char(PyUnicode_AsWideCharStringRet0);
		PyMem_Free(PyUnicode_AsWideCharStringRet0);
		eventdata.datas = datas;
		free(datas);
	}

	ClientApp::getSingleton().fireEvent(&eventdata);
	S_Return;
}
Beispiel #5
0
//-------------------------------------------------------------------------------------
PyObject* EntityComponent::onScriptGetAttribute(PyObject* attr)
{
	wchar_t* PyUnicode_AsWideCharStringRet0 = PyUnicode_AsWideCharString(attr, NULL);
	char* ccattr = strutil::wchar2char(PyUnicode_AsWideCharStringRet0);
	PyMem_Free(PyUnicode_AsWideCharStringRet0);

	free(ccattr);
	return ScriptObject::onScriptGetAttribute(attr);
}
static PyObject *Rainmeter_RmReadDouble(RainmeterObject *self, PyObject *args)
{
	PyObject *option;
	double defValue;
	PyArg_ParseTuple(args, "Ud", &option, &defValue);
	wchar_t *optionStr = PyUnicode_AsWideCharString(option, NULL);
	double result = RmReadDouble(self->rm, optionStr, defValue);
	PyMem_Free(optionStr);
	return PyFloat_FromDouble(result);
}
static PyObject *Rainmeter_RmReadInt(RainmeterObject *self, PyObject *args)
{
	PyObject *option;
	int defValue;
	PyArg_ParseTuple(args, "Ui", &option, &defValue);
	wchar_t *optionStr = PyUnicode_AsWideCharString(option, NULL);
	int result = RmReadInt(self->rm, optionStr, defValue);
	PyMem_Free(optionStr);
	return PyLong_FromLong(result);
}
static PyObject *Rainmeter_RmExecute(RainmeterObject *self, PyObject *args)
{
	PyObject *command;
	PyArg_ParseTuple(args, "U", &command);
	wchar_t *commandStr = PyUnicode_AsWideCharString(command, NULL);
	RmExecute(RmGetSkin(self->rm), commandStr);
	PyMem_Free(commandStr);
	Py_INCREF(Py_None);
	return Py_None;
}
static PyObject *Rainmeter_RmLog(RainmeterObject *self, PyObject *args)
{
	int level;
	PyObject *message;
	PyArg_ParseTuple(args, "iU", &level, &message);
	wchar_t *messageStr = PyUnicode_AsWideCharString(message, NULL);
	RmLog(level, messageStr);
	PyMem_Free(messageStr);
	Py_INCREF(Py_None);
	return Py_None;
}
Beispiel #10
0
//-------------------------------------------------------------------------------------
PyObject* ClientEntity::onScriptGetAttribute(PyObject* attr)
{
	Entity* srcEntity = Cellapp::getSingleton().findEntity(srcEntityID_);

	if(srcEntity == NULL)
	{
		PyErr_Format(PyExc_AssertionError, "Entity::clientEntity: srcEntityID(%d) not found!\n",		
			 srcEntityID_);		
		PyErr_PrintEx(0);
		return 0;
	}

	if(srcEntity->isDestroyed())
	{
		PyErr_Format(PyExc_AssertionError, "Entity::clientEntity: srcEntityID(%d) is destroyed!\n",		
			srcEntityID_);		
		PyErr_PrintEx(0);
		return 0;
	}

	if(srcEntity->pWitness() == NULL)
	{
		PyErr_Format(PyExc_AssertionError, "%s::clientEntity: no client, srcEntityID(%d).\n",		
			srcEntity->scriptName(), srcEntity->id());		
		PyErr_PrintEx(0);
		return 0;
	}

	EntityRef* pEntityRef = srcEntity->pWitness()->getAOIEntityRef(clientEntityID_);
	Entity* e = (pEntityRef && ((pEntityRef->flags() & ENTITYREF_FLAG_ENTER_CLIENT_PENDING) <= 0))
		? pEntityRef->pEntity() : NULL;

	if(e == NULL)
	{
		PyErr_Format(PyExc_AssertionError, "%s::clientEntity: not found entity(%d), srcEntityID(%d).\n",		
			srcEntity->scriptName(), clientEntityID_, srcEntity->id());		
		PyErr_PrintEx(0);
		return 0;
	}

	wchar_t* PyUnicode_AsWideCharStringRet0 = PyUnicode_AsWideCharString(attr, NULL);
	char* ccattr = strutil::wchar2char(PyUnicode_AsWideCharStringRet0);
	PyMem_Free(PyUnicode_AsWideCharStringRet0);

	MethodDescription* pMethodDescription = const_cast<ScriptDefModule*>(e->pScriptModule())->findClientMethodDescription(ccattr);
	free(ccattr);

	if(pMethodDescription != NULL)
	{
		return new ClientEntityMethod(pMethodDescription, srcEntityID_, clientEntityID_);
	}

	return ScriptObject::onScriptGetAttribute(attr);
}
Beispiel #11
0
static PyObject *
Z_set(void *ptr, PyObject *value, Py_ssize_t size)
{
    if (value == Py_None) {
        *(wchar_t **)ptr = NULL;
        Py_INCREF(value);
        return value;
    }
    if (PyLong_Check(value) || PyLong_Check(value)) {
#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
        *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongLongMask(value);
#else
        *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongMask(value);
#endif
        Py_INCREF(Py_None);
        return Py_None;
    }
    if (!PyUnicode_Check(value)) {
        PyErr_Format(PyExc_TypeError,
                     "unicode string or integer address expected instead of %s instance",
                     value->ob_type->tp_name);
        return NULL;
    } else
        Py_INCREF(value);
#if Py_UNICODE_SIZE == SIZEOF_WCHAR_T
    /* We can copy directly.  Hm, are unicode objects always NUL
       terminated in Python, internally?
     */
    *(wchar_t **)ptr = (wchar_t *) PyUnicode_AS_UNICODE(value);
    return value;
#else
    {
        /* We must create a wchar_t* buffer from the unicode object,
           and keep it alive */
        PyObject *keep;
        wchar_t *buffer;

        buffer = PyUnicode_AsWideCharString(value, NULL);
        if (!buffer) {
            Py_DECREF(value);
            return NULL;
        }
        keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor);
        if (!keep) {
            Py_DECREF(value);
            PyMem_Free(buffer);
            return NULL;
        }
        *(wchar_t **)ptr = (wchar_t *)buffer;
        Py_DECREF(value);
        return keep;
    }
#endif
}
//-------------------------------------------------------------------------------------
void SpaceAvatarSelect::kbengine_onEvent(const KBEngine::EventData* lpEventData)
{
	switch(lpEventData->id)
	{
		case CLIENT_EVENT_SCRIPT:
			{
				const KBEngine::EventData_Script* peventdata = static_cast<const KBEngine::EventData_Script*>(lpEventData);
				if(peventdata->name == "update_avatars")
				{
					if(peventdata->argsSize > 0)
					{
						PyObject* pyitem = PyTuple_GetItem(peventdata->pyDatas, 0);
						for(KBEngine::uint32 i=0; i<g_avatars.size(); i++)
						{
							mTrayMgr->destroyWidget(g_avatars[i]);
						}
						
						g_avatars.clear();

						PyObject *key, *value;
						Py_ssize_t pos = 0;
						while (PyDict_Next(pyitem, &pos, &key, &value)) 
						{
							wchar_t* PyUnicode_AsWideCharStringRet0 = PyUnicode_AsWideCharString(PyDict_GetItemString(value, "name"), NULL);
							char* name = wchar2char(PyUnicode_AsWideCharStringRet0);
							PyMem_Free(PyUnicode_AsWideCharStringRet0);
							
							KBEngine::DBID dbid = 0;
							dbid = PyLong_AsUnsignedLongLong(key);
 							if (PyErr_Occurred())																	
 							{																						
								dbid = PyLong_AsUnsignedLong(key);														
							}	
 							if (PyErr_Occurred())																	
 							{																						
								PyErr_PrintEx(0);																	
							}	

							Ogre::String str = Ogre::String(name) + "_" + KBEngine::StringConv::val2str(dbid);
							g_avatars.push_back(str);
							mTrayMgr->createButton(OgreBites::TL_CENTER, str, str, 300);

							free(name);
						}																					
					}
				}
			}
			break;
		default:
			break;
	};
}
Beispiel #13
0
//-------------------------------------------------------------------------------------
FileDataDownload::FileDataDownload(PyObjectPtr objptr, 
							const std::string & descr, int16 id):
DataDownload(objptr, descr, id)
{
	wchar_t* PyUnicode_AsWideCharStringRet1 = PyUnicode_AsWideCharString(objptr.get(), NULL);
	char* pDescr = strutil::wchar2char(PyUnicode_AsWideCharStringRet1);
	PyMem_Free(PyUnicode_AsWideCharStringRet1);

	path_ = pDescr;
	free(pDescr);

	stream_ = new char[65537];
}
Beispiel #14
0
extern "C" __declspec(dllexport) long __cdecl ExecuteFunction(const char *name, const char *args, wchar_t **value)
{
	PyObject *result = PyObject_CallMethod(iface, "exec_func", "ss", name, args);
	static wchar_t *text = NULL;
	if (text != NULL)
	{
		PyMem_Free(text);
		text = NULL;
	}

	if (result != NULL) 
	{
		text = PyUnicode_AsWideCharString(result, NULL);
		*value = (wchar_t *) text;
		Py_DECREF(result);
		return 0;
	}
	else
	{
	

	PyObject* excType, *excValue, *excTraceback;
    PyErr_Fetch(&excType, &excValue, &excTraceback);
    PyErr_NormalizeException(&excType, &excValue, &excTraceback);

	PyObject *mod = PyImport_ImportModule("traceback");
	PyObject *list = PyObject_CallMethod(mod, "format_exception", "OOO", excType, excValue, excTraceback);
	PyObject *separator = PyUnicode_FromString("\n");
	PyObject *exc_info = PyUnicode_Join(separator, list);

	text = PyUnicode_AsWideCharString(exc_info, NULL);
	*value = (wchar_t *) text;

		PyErr_Print();
		return -1;
	}

}
Beispiel #15
0
static PyObject*
PyLocale_strcoll(PyObject* self, PyObject* args)
{
    PyObject *os1, *os2, *result = NULL;
    wchar_t *ws1 = NULL, *ws2 = NULL;

    if (!PyArg_ParseTuple(args, "UU:strcoll", &os1, &os2))
        return NULL;
    /* Convert the unicode strings to wchar[]. */
    ws1 = PyUnicode_AsWideCharString(os1, NULL);
    if (ws1 == NULL)
        goto done;
    ws2 = PyUnicode_AsWideCharString(os2, NULL);
    if (ws2 == NULL)
        goto done;
    /* Collate the strings. */
    result = PyLong_FromLong(wcscoll(ws1, ws2));
  done:
    /* Deallocate everything. */
    if (ws1) PyMem_FREE(ws1);
    if (ws2) PyMem_FREE(ws2);
    return result;
}
Beispiel #16
0
//-------------------------------------------------------------------------------------
PyObject* ScriptStdOut::__py_write(PyObject* self, PyObject *args)
{
	PyObject* obj = NULL;

	if (!PyArg_ParseTuple(args, "O", &obj))
	{
		ERROR_MSG("ScriptStdOut::write: Bad args\n");
		return NULL;
	}
		
	Py_ssize_t size = 0;
	wchar_t* PyUnicode_AsWideCharStringRet0 = PyUnicode_AsWideCharString(obj, &size);
	static_cast<ScriptStdOut*>(self)->pScriptStdOutErr()->info_msg(PyUnicode_AsWideCharStringRet0, (uint32)size);
	PyMem_Free(PyUnicode_AsWideCharStringRet0);
	S_Return;
}
//-------------------------------------------------------------------------------------
PyObject* AllClients::onScriptGetAttribute(PyObject* attr)
{
	wchar_t* PyUnicode_AsWideCharStringRet0 = PyUnicode_AsWideCharString(attr, NULL);
	char* ccattr = strutil::wchar2char(PyUnicode_AsWideCharStringRet0);
	PyMem_Free(PyUnicode_AsWideCharStringRet0);

	MethodDescription* md = const_cast<ScriptDefModule*>(scriptModule_)->findClientMethodDescription(ccattr);
	
	if(md != NULL)
	{
		free(ccattr);
		return new ClientsRemoteEntityMethod(md, otherClients_, id_);
	}

	free(ccattr);
	return ScriptObject::onScriptGetAttribute(attr);
}
Beispiel #18
0
//-------------------------------------------------------------------------------------
int FixedDict::mp_ass_subscript(PyObject* self, PyObject* key, PyObject* value)
{
	wchar_t* PyUnicode_AsWideCharStringRet0 = PyUnicode_AsWideCharString(key, NULL);
	if (PyUnicode_AsWideCharStringRet0 == NULL)
	{
		char err[255];
		kbe_snprintf(err, 255, "FixedDict::mp_ass_subscript: key not is string!\n");
		PyErr_SetString(PyExc_TypeError, err);
		PyErr_PrintEx(0);
		return 0;
	}

	char* dictKeyName = strutil::wchar2char(PyUnicode_AsWideCharStringRet0);
	PyMem_Free(PyUnicode_AsWideCharStringRet0);

	FixedDict* fixedDict = static_cast<FixedDict*>(self);
	if (value == NULL)
	{
		if(!fixedDict->checkDataChanged(dictKeyName, value, true))
		{
			free(dictKeyName);
			return 0;
		}

		free(dictKeyName);
		return PyDict_DelItem(fixedDict->pyDict_, key);
	}
	
	if(!fixedDict->checkDataChanged(dictKeyName, value))
	{
		free(dictKeyName);
		return 0;
	}

	PyObject* val1 = 
		static_cast<FixedDictType*>(fixedDict->getDataType())->createNewItemFromObj(dictKeyName, value);

	int ret = PyDict_SetItem(fixedDict->pyDict_, key, val1);
	
	// 由于PyDict_SetItem会增加引用因此需要减
	Py_DECREF(val1);

	free(dictKeyName);
	return ret;
}
Beispiel #19
0
static PyObject*
PyLocale_strxfrm(PyObject* self, PyObject* args)
{
    PyObject *str;
    Py_ssize_t n1;
    wchar_t *s = NULL, *buf = NULL;
    size_t n2;
    PyObject *result = NULL;

    if (!PyArg_ParseTuple(args, "U:strxfrm", &str))
        return NULL;

    s = PyUnicode_AsWideCharString(str, &n1);
    if (s == NULL)
        goto exit;

    /* assume no change in size, first */
    n1 = n1 + 1;
    buf = PyMem_New(wchar_t, n1);
    if (!buf) {
        PyErr_NoMemory();
        goto exit;
    }
    n2 = wcsxfrm(buf, s, n1);
    if (n2 >= (size_t)n1) {
        /* more space needed */
        wchar_t * new_buf = PyMem_Realloc(buf, (n2+1)*sizeof(wchar_t));
        if (!new_buf) {
            PyErr_NoMemory();
            goto exit;
        }
        buf = new_buf;
        n2 = wcsxfrm(buf, s, n2+1);
    }
    result = PyUnicode_FromWideChar(buf, n2);
exit:
    if (buf)
        PyMem_Free(buf);
    if (s)
        PyMem_Free(s);
    return result;
}
Beispiel #20
0
//-------------------------------------------------------------------------------------		
PyObject* ClientApp::__py_fireEvent(PyObject* self, PyObject* args)
{
	if(PyTuple_Size(args) < 1)
	{
		PyErr_Format(PyExc_AssertionError, "ClientApp::fireEvent: arg1(eventName) not found!\n");
		PyErr_PrintEx(0);
		return NULL;
	}

	PyObject* pyname = PyTuple_GetItem(args, 0);

	if(!pyname || !PyUnicode_Check(pyname))
	{
		PyErr_Format(PyExc_AssertionError, "ClientApp::fireEvent: arg1(eventName) not found!\n");
		PyErr_PrintEx(0);
		return NULL;
	}

	wchar_t* PyUnicode_AsWideCharStringRet0 = PyUnicode_AsWideCharString(pyname, NULL);
	char* name = strutil::wchar2char(PyUnicode_AsWideCharStringRet0);
	PyMem_Free(PyUnicode_AsWideCharStringRet0);

	EventData_Script eventdata;
	eventdata.name = name;
	eventdata.argsSize = PyTuple_Size(args) - 1;
	free(name);

	if(eventdata.argsSize > 0)
	{
		eventdata.pyDatas = PyTuple_New(eventdata.argsSize + 1);
		for(uint32 i=0; i<eventdata.argsSize; i++)
		{
			PyObject* pyitem = PyTuple_GetItem(args, i + 1);
			PyTuple_SetItem(eventdata.pyDatas, i, pyitem);
			Py_INCREF(pyitem);
		}
	}

	ClientApp::getSingleton().fireEvent(&eventdata);
	S_Return;
}
Beispiel #21
0
static PyObject *
Z_set(void *ptr, PyObject *value, Py_ssize_t size)
{
    PyObject *keep;
    wchar_t *buffer;

    if (value == Py_None) {
        *(wchar_t **)ptr = NULL;
        Py_INCREF(value);
        return value;
    }
    if (PyLong_Check(value) || PyLong_Check(value)) {
#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
        *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongLongMask(value);
#else
        *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongMask(value);
#endif
        Py_INCREF(Py_None);
        return Py_None;
    }
    if (!PyUnicode_Check(value)) {
        PyErr_Format(PyExc_TypeError,
                     "unicode string or integer address expected instead of %s instance",
                     value->ob_type->tp_name);
        return NULL;
    }

    /* We must create a wchar_t* buffer from the unicode object,
       and keep it alive */
    buffer = PyUnicode_AsWideCharString(value, NULL);
    if (!buffer)
        return NULL;
    keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor);
    if (!keep) {
        PyMem_Free(buffer);
        return NULL;
    }
    *(wchar_t **)ptr = buffer;
    return keep;
}
Beispiel #22
0
//-------------------------------------------------------------------------------------
static PyObject* delWatcher(PyObject* self, PyObject* args)
{
    if(PyTuple_Size(args) != 1)
    {
        PyErr_Format(PyExc_Exception, "KBEngine::delWatcher: watcherName is error!\n");
        PyErr_PrintEx(0);
        return NULL;
    }

    PyObject* pyName = NULL;

    if(PyArg_ParseTuple(args, "O", &pyName) == -1)
    {
        PyErr_Format(PyExc_Exception, "KBEngine::delWatcher: watcherName is error!\n");
        PyErr_PrintEx(0);
        return NULL;
    }

    if(!PyUnicode_Check(pyName))
    {
        PyErr_Format(PyExc_Exception, "KBEngine::delWatcher: watcherName is error!\n");
        PyErr_PrintEx(0);
        return NULL;
    }

    wchar_t* wstr = PyUnicode_AsWideCharString(pyName, NULL);
    char* pwatchername = strutil::wchar2char(wstr);
    PyMem_Free(wstr);

    bool ret = _delWatcher(pwatchername);
    free(pwatchername);

    if(!ret)
    {
        Py_RETURN_FALSE;
    }

    Py_RETURN_TRUE;
}
Beispiel #23
0
static PyObject *
time_strftime(PyObject *self, PyObject *args)
{
    PyObject *tup = NULL;
    struct tm buf;
    const time_char *fmt;
#ifdef HAVE_WCSFTIME
    wchar_t *format;
#else
    PyObject *format;
#endif
    PyObject *format_arg;
    size_t fmtlen, buflen;
    time_char *outbuf = NULL;
    size_t i;
    PyObject *ret = NULL;

    memset((void *) &buf, '\0', sizeof(buf));

    /* Will always expect a unicode string to be passed as format.
       Given that there's no str type anymore in py3k this seems safe.
    */
    if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
        return NULL;

    if (tup == NULL) {
        time_t tt = time(NULL);
        if (pylocaltime(&tt, &buf) == -1)
            return NULL;
    }
    else if (!gettmarg(tup, &buf) || !checktm(&buf))
        return NULL;

#if defined(_MSC_VER) || defined(sun) || defined(_AIX)
    if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
        PyErr_SetString(PyExc_ValueError,
                        "strftime() requires year in [1; 9999]");
        return NULL;
    }
#endif

    /* Normalize tm_isdst just in case someone foolishly implements %Z
       based on the assumption that tm_isdst falls within the range of
       [-1, 1] */
    if (buf.tm_isdst < -1)
        buf.tm_isdst = -1;
    else if (buf.tm_isdst > 1)
        buf.tm_isdst = 1;

#ifdef HAVE_WCSFTIME
    format = PyUnicode_AsWideCharString(format_arg, NULL);
    if (format == NULL)
        return NULL;
    fmt = format;
#else
    /* Convert the unicode string to an ascii one */
    format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
    if (format == NULL)
        return NULL;
    fmt = PyBytes_AS_STRING(format);
#endif

#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
    /* check that the format string contains only valid directives */
    for(outbuf = strchr(fmt, '%');
        outbuf != NULL;
        outbuf = strchr(outbuf+2, '%'))
    {
        if (outbuf[1]=='#')
            ++outbuf; /* not documented by python, */
        if (outbuf[1]=='\0' ||
            !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
        {
            PyErr_SetString(PyExc_ValueError, "Invalid format string");
            Py_DECREF(format);
            return NULL;
        }
        if ((outbuf[1] == 'y') && buf.tm_year < 0)
        {
            PyErr_SetString(PyExc_ValueError,
                        "format %y requires year >= 1900 on Windows");
            Py_DECREF(format);
            return NULL;
        }
    }
#elif (defined(_AIX) || defined(sun)) && defined(HAVE_WCSFTIME)
    for(outbuf = wcschr(fmt, '%');
        outbuf != NULL;
        outbuf = wcschr(outbuf+2, '%'))
    {
        if (outbuf[1] == L'\0')
            break;
        /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
           returns "0/" instead of "99" */
        if (outbuf[1] == L'y' && buf.tm_year < 0) {
            PyErr_SetString(PyExc_ValueError,
                            "format %y requires year >= 1900 on AIX");
            return NULL;
        }
    }
#endif

    fmtlen = time_strlen(fmt);

    /* I hate these functions that presume you know how big the output
     * will be ahead of time...
     */
    for (i = 1024; ; i += i) {
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
        int err;
#endif
        outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
        if (outbuf == NULL) {
            PyErr_NoMemory();
            break;
        }
        buflen = format_time(outbuf, i, fmt, &buf);
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
        err = errno;
#endif
        if (buflen > 0 || i >= 256 * fmtlen) {
            /* If the buffer is 256 times as long as the format,
               it's probably not failing for lack of room!
               More likely, the format yields an empty result,
               e.g. an empty format, or %Z when the timezone
               is unknown. */
#ifdef HAVE_WCSFTIME
            ret = PyUnicode_FromWideChar(outbuf, buflen);
#else
            ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
                                                "surrogateescape");
#endif
            PyMem_Free(outbuf);
            break;
        }
        PyMem_Free(outbuf);
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
        /* VisualStudio .NET 2005 does this properly */
        if (buflen == 0 && err == EINVAL) {
            PyErr_SetString(PyExc_ValueError, "Invalid format string");
            break;
        }
#endif
    }
#ifdef HAVE_WCSFTIME
    PyMem_Free(format);
#else
    Py_DECREF(format);
#endif
    return ret;
}
Beispiel #24
0
//-------------------------------------------------------------------------------------
static PyObject* addWatcher(PyObject* self, PyObject* args)
{
	if(PyTuple_Size(args) != 3)
	{
		PyErr_Format(PyExc_Exception, "KBEngine::addWatcher: args is error! "
			"arg(watcherName, deftype[UINT32|STRING...], pyCallable).\n");
		PyErr_PrintEx(0);
		return NULL;
	}

	PyObject* pyName = NULL;
	PyObject* pyType = NULL;
	PyObject* pyObj = NULL;
	
	if(PyArg_ParseTuple(args, "O|O|O", &pyName, &pyType, &pyObj) == -1)
	{
		PyErr_Format(PyExc_Exception, "KBEngine::addWatcher: args is error! "
			"arg(watcherPath, deftype[UINT32|STRING...], pyCallable).\n");
		PyErr_PrintEx(0);
		return NULL;
	}

	if(!PyUnicode_Check(pyName))
	{
		PyErr_Format(PyExc_Exception, "KBEngine::addWatcher: args1 is error! "
			"arg=watcherPath\n");
		PyErr_PrintEx(0);
		return NULL;
	}

	if(!PyUnicode_Check(pyType))
	{
		PyErr_Format(PyExc_Exception, "KBEngine::addWatcher: args2 is error! "
			"arg=deftype[UINT32|STRING...]\n");
		PyErr_PrintEx(0);
		return NULL;
	}

	wchar_t* wstr = PyUnicode_AsWideCharString(pyName, NULL);					
	char* pwatchername = strutil::wchar2char(wstr);	
	std::string watchername = pwatchername;
	PyMem_Free(wstr);	
	free(pwatchername);

	wstr = PyUnicode_AsWideCharString(pyType, NULL);					
	pwatchername = strutil::wchar2char(wstr);	
	std::string type = pwatchername;
	PyMem_Free(wstr);	
	free(pwatchername);

	PyObject* pyObj1 = NULL;

	if(!PyCallable_Check(pyObj))
	{
		PyErr_Format(PyExc_Exception, "Baseapp::createBase: args3 is error! "
			"arg=pyCallable.\n");
		PyErr_PrintEx(0);
		return NULL;
	}

	pyObj1 = PyObject_CallFunction(pyObj, const_cast<char*>(""));
	if(!pyObj1)
	{
		PyErr_Clear();
		PyErr_Format(PyExc_Exception, "Baseapp::createBase: return is error for args3! "
			"arg=pyCallable.\n");
		PyErr_PrintEx(0);
		return NULL;
	}
	
	Py_INCREF(pyObj);

	if(strcmp("UINT8", type.c_str()) == 0)
	{
		_addWatcher<uint8>(pwatchername, pyObj);
	}
	else if(strcmp("UINT16", type.c_str()) == 0)
	{
		_addWatcher<uint16>(pwatchername, pyObj);
	}
	else if(strcmp("UINT32", type.c_str()) == 0)
	{
		_addWatcher<uint32>(pwatchername, pyObj);
	}
	else if(strcmp("UINT64", type.c_str()) == 0)
	{
		_addWatcher<uint64>(pwatchername, pyObj);
	}
	else if(strcmp("INT8", type.c_str()) == 0)
	{
		_addWatcher<int8>(pwatchername, pyObj);
	}
	else if(strcmp("INT16", type.c_str()) == 0)
	{
		_addWatcher<int16>(pwatchername, pyObj);
	}
	else if(strcmp("INT32", type.c_str()) == 0)
	{
		_addWatcher<int32>(pwatchername, pyObj);
	}
	else if(strcmp("INT64", type.c_str()) == 0)
	{
		_addWatcher<int64>(pwatchername, pyObj);
	}
	else if(strcmp("FLOAT", type.c_str()) == 0)
	{
		_addWatcher<float>(pwatchername, pyObj);
	}
	else if(strcmp("DOUBLE", type.c_str()) == 0)
	{
		_addWatcher<double>(pwatchername, pyObj);
	}
	else if(strcmp("BOOL", type.c_str()) == 0)
	{
		_addWatcher<uint8>(pwatchername, pyObj);
	}
	else if(strcmp("STRING", type.c_str()) == 0)
	{
		_addWatcher<std::string>(pwatchername, pyObj);
	}

	Py_DECREF(pyObj1);
	S_Return;
}
Beispiel #25
0
	}
	else
	{
		this->hasDB(false);
	}

	shouldAutoArchive_ = 0;
	shouldAutoBackup_ = 0;
}

//-------------------------------------------------------------------------------------
PyObject* Base::onScriptGetAttribute(PyObject* attr)
{
	DEBUG_OP_ATTRIBUTE("get", attr)
		
	wchar_t* PyUnicode_AsWideCharStringRet0 = PyUnicode_AsWideCharString(attr, NULL);
	char* ccattr = strutil::wchar2char(PyUnicode_AsWideCharStringRet0);
	PyMem_Free(PyUnicode_AsWideCharStringRet0);
	
	// 如果访问了def持久化类容器属性
	// 由于没有很好的监测容器类属性内部的变化,这里使用一个折中的办法进行标脏
	PropertyDescription* pPropertyDescription = const_cast<ScriptDefModule*>(pScriptModule())->findPersistentPropertyDescription(ccattr);
	if(pPropertyDescription && (pPropertyDescription->getFlags() & ENTITY_BASE_DATA_FLAGS) > 0)
	{
		setDirty();
	}
	else if (strcmp(ccattr, "cellData") == 0)
	{
		setDirty();
	}
	
Beispiel #26
0
PyObject* EntityApp<E>::__py_listPathRes(PyObject* self, PyObject* args)
{
	int argCount = PyTuple_Size(args);
	if(argCount < 1 || argCount > 2)
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path, pathargs=\'*.*\'] is error!");
		PyErr_PrintEx(0);
		return 0;
	}

	std::wstring wExtendName = L"*";
	PyObject* pathobj = NULL;
	PyObject* path_argsobj = NULL;

	if(argCount == 1)
	{
		if(PyArg_ParseTuple(args, "O", &pathobj) == -1)
		{
			PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is error!");
			PyErr_PrintEx(0);
			return 0;
		}
	}
	else
	{
		if(PyArg_ParseTuple(args, "O|O", &pathobj, &path_argsobj) == -1)
		{
			PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path, pathargs=\'*.*\'] is error!");
			PyErr_PrintEx(0);
			return 0;
		}
		
		if(PyUnicode_Check(path_argsobj))
		{
			wchar_t* fargs = NULL;
			fargs = PyUnicode_AsWideCharString(path_argsobj, NULL);
			wExtendName = fargs;
			PyMem_Free(fargs);
		}
		else
		{
			if(PySequence_Check(path_argsobj))
			{
				wExtendName = L"";
				Py_ssize_t size = PySequence_Size(path_argsobj);
				for(int i=0; i<size; i++)
				{
					PyObject* pyobj = PySequence_GetItem(path_argsobj, i);
					if(!PyUnicode_Check(pyobj))
					{
						PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path, pathargs=\'*.*\'] is error!");
						PyErr_PrintEx(0);
						return 0;
					}
					
					wchar_t* wtemp = NULL;
					wtemp = PyUnicode_AsWideCharString(pyobj, NULL);
					wExtendName += wtemp;
					wExtendName += L"|";
					PyMem_Free(wtemp);
				}
			}
			else
			{
				PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[pathargs] is error!");
				PyErr_PrintEx(0);
				return 0;
			}
		}
	}

	if(!PyUnicode_Check(pathobj))
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is error!");
		PyErr_PrintEx(0);
		return 0;
	}

	if(wExtendName.size() == 0)
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[pathargs] is NULL!");
		PyErr_PrintEx(0);
		return 0;
	}

	if(wExtendName[0] == '.')
		wExtendName.erase(wExtendName.begin());

	if(wExtendName.size() == 0)
		wExtendName = L"*";

	wchar_t* respath = PyUnicode_AsWideCharString(pathobj, NULL);
	if(respath == NULL)
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is NULL!");
		PyErr_PrintEx(0);
		return 0;
	}

	char* cpath = strutil::wchar2char(respath);
	std::string foundPath = Resmgr::getSingleton().matchPath(cpath);
	free(cpath);
	PyMem_Free(respath);

	respath = strutil::char2wchar(foundPath.c_str());

	std::vector<std::wstring> results;
	Resmgr::getSingleton().listPathRes(respath, wExtendName, results);
	PyObject* pyresults = PyTuple_New(results.size());

	std::vector<std::wstring>::iterator iter = results.begin();
	int i = 0;

	for(; iter != results.end(); iter++)
	{
		PyTuple_SET_ITEM(pyresults, i++, PyUnicode_FromWideChar((*iter).c_str(), (*iter).size()));
	}

	free(respath);
	return pyresults;
}
Beispiel #27
0
/*	Converts Python simple objects (String, Long, Float, Boolean, Bytes, and None) to C string.
	If the `obj` is none of these types raise BadInternalCall() error and return NULL.
*/
char *
PyObject2char(PyObject *obj) {
	char *str = NULL;
	char *tmp = NULL;
	const wchar_t *wstr;
	Py_ssize_t length = 0;
	const unsigned int len = 24; /* The max length that a number's char* representation can be. */

	if (obj == NULL) return NULL;

	/* If Python objects is a None return an empty("") char*. */
	if (obj == Py_None) {
		str = (char *)malloc(sizeof(char));
		str[0] = '\0';
		return str;
	}
	if (PyUnicode_Check(obj)) {
		/* Python string converting. From Python 3.3 could be use PyUnicode_AsUTF8AndSize(). */
		wstr = PyUnicode_AsWideCharString(obj, &length);
		str = (char *)malloc(sizeof(char) * (length + 1));
		if (str == NULL) return (char *)PyErr_NoMemory();
		wcstombs(str, wstr, length);
		/* Put the delimiter at the end. */
		str[length] = '\0';
	} else if (PyLong_Check(obj)) {
		/* Python integer converting. Could be longer, literally. */
		long int inum = PyLong_AsLong(obj);
		tmp = malloc(sizeof(char) * len);
		if (tmp == NULL) return (char *)PyErr_NoMemory();
		sprintf(tmp, "%ld", inum);
	} else if (PyFloat_Check(obj)) {
		/* Python floating point number converting. */
		double dnum = PyFloat_AsDouble(obj);
		tmp = malloc(sizeof(char) * len);
		if (tmp == NULL) return (char *)PyErr_NoMemory();
		sprintf(tmp, "%lf", dnum);
	} else if (PyBool_Check(obj)) {
		/* Python boolean converting to number representation (0 or 1). */
		if (obj == Py_True) {
			str = "1";
		} else {
			str = "0";
		}
	} else if (PyBytes_Check(obj)) {
		/* Python bytes converting. */
		tmp = PyBytes_AsString(obj);
		if (tmp == NULL) return NULL;
		str = (char *)malloc(sizeof(char) * (strlen(tmp) + 1));
		strcpy(str, tmp);
		return str;
	} else {
		PyErr_BadInternalCall();
		return NULL;
	}
	/* In case of converting numbers, optimizing the memory allocation. */
	if (tmp != NULL) {
		str = strdup(tmp);
		free(tmp);
	}
	return str;
}
Beispiel #28
0
//-------------------------------------------------------------------------------------
PyObject* ClientEntity::onScriptGetAttribute(PyObject* attr)
{
	Entity* srcEntity = Cellapp::getSingleton().findEntity(srcEntityID_);

	if(srcEntity == NULL)
	{
		PyErr_Format(PyExc_AssertionError, "Entity::clientEntity: srcEntityID(%d) not found!\n",		
			 srcEntityID_);		
		PyErr_PrintEx(0);
		return 0;
	}

	if(srcEntity->isDestroyed())
	{
		PyErr_Format(PyExc_AssertionError, "Entity::clientEntity: srcEntityID(%d) is destroyed!\n",		
			srcEntityID_);		
		PyErr_PrintEx(0);
		return 0;
	}

	if(srcEntity->pWitness() == NULL)
	{
		PyErr_Format(PyExc_AssertionError, "%s::clientEntity: no client, srcEntityID(%d).\n",		
			srcEntity->getScriptName(), srcEntity->getID());		
		PyErr_PrintEx(0);
		return 0;
	}

	EntityRef::AOI_ENTITIES::iterator iter = srcEntity->pWitness()->aoiEntities().begin();
	Entity* e = NULL;

	for(; iter != srcEntity->pWitness()->aoiEntities().end(); iter++)
	{
		if((*iter)->id() == clientEntityID_ && ((*iter)->flags() & ENTITYREF_FLAG_ENTER_CLIENT_PENDING) <= 0)
		{
			e = (*iter)->pEntity();
			break;
		}
	}

	if(e == NULL)
	{
		PyErr_Format(PyExc_AssertionError, "%s::clientEntity: not found entity(%d), srcEntityID(%d).\n",		
			srcEntity->getScriptName(), clientEntityID_, srcEntity->getID());		
		PyErr_PrintEx(0);
		return 0;
	}

	wchar_t* PyUnicode_AsWideCharStringRet0 = PyUnicode_AsWideCharString(attr, NULL);
	char* ccattr = strutil::wchar2char(PyUnicode_AsWideCharStringRet0);
	PyMem_Free(PyUnicode_AsWideCharStringRet0);

	MethodDescription* md = const_cast<ScriptDefModule*>(e->getScriptModule())->findClientMethodDescription(ccattr);
	free(ccattr);

	if(md != NULL)
	{
		return new ClientEntityMethod(md, srcEntityID_, clientEntityID_);
	}

	return ScriptObject::onScriptGetAttribute(attr);
}
CString BZScriptPython::run(CBZScriptView* sview, const char * cmdstr)
{
	cbzsv = sview;

	// referring IDAPython PythonEvalOrExec..
	PyCompilerFlags cf = {0};
	PyObject *py_code = Py_CompileStringFlags(cmdstr, "<string>", Py_eval_input, &cf);
	if(py_code == NULL || PyErr_Occurred())
	{
		// Not an expression?
		PyErr_Clear();

		// Run as a string
		PyRun_SimpleString(cmdstr);
		return _T("");
	}

	PyObject *module = PyImport_AddModule("__main__");
	PyObject *py_globals = (module == NULL) ? NULL : PyModule_GetDict(module);
	//PYW_GIL_ENSURE;
#ifdef BZPYTHON2
	PyObject *py_result = PyEval_EvalCode((PyCodeObject*)py_code, py_globals, py_globals);
#endif
#ifdef BZPYTHON3
	PyObject *py_result = PyEval_EvalCode(py_code, py_globals, py_globals);
#endif
	//PYW_GIL_RELEASE;
	Py_DECREF(py_code);

	if(py_result == NULL || PyErr_Occurred())
	{
		PyErr_Print();
		return _T("");
	}
	if(py_result != Py_None)
	{
		PyObject *pystr = PyObject_Str(py_result);
		Py_DECREF(py_result);
#ifdef BZPYTHON2
		char *cstr = PyString_AsString(pystr);
		int cstrlen = strlen(cstr);
		CStringA csresult(cstr, cstrlen);
#endif
#ifdef BZPYTHON3
		// PyUnicode_AsUnicode->Py_UNICODE could be UCS4... only want wchar_t; use PyUnicode_AsWideChar(String).
		wchar_t *cstr = PyUnicode_AsWideCharString(pystr, NULL);
		int cstrlen = lstrlenW(cstr);
		CStringW csresult(cstr, cstrlen);
		PyMem_Free(cstr);
#endif
		Py_DECREF(pystr);
		CString csnative(csresult);
		CString ostr;

		csnative.Replace(_T("\n"), _T("\r\n"));
		ostr.Format(_T("%s\r\n"), csnative);

		return ostr;
	}

	Py_DECREF(py_result);

	return _T("");//ostr;
}
Beispiel #30
0
//-------------------------------------------------------------------------------------
PyObject* Proxy::__py_pyStreamStringToClient(PyObject* self, PyObject* args)
{
	uint16 currargsSize = PyTuple_Size(args);
	Proxy* pobj = static_cast<Proxy*>(self);

	if(pobj->clientMailbox() == NULL)
	{
		PyErr_Format(PyExc_AssertionError,
						"Proxy::streamStringToClient: has no client.");
		PyErr_PrintEx(0);
		return NULL;
	}

	if(currargsSize > 3 || currargsSize == 0)
	{
		PyErr_Format(PyExc_AssertionError,
						"Proxy::streamStringToClient: args max require 3, gived %d! is script[%s].\n",
			currargsSize, pobj->scriptName());
		PyErr_PrintEx(0);
		return NULL;
	}

	PyObject* pyData = NULL;
	PyObject* pyDesc = NULL;
	int16 id = -1;

	if(currargsSize == 1)
	{
		if(PyArg_ParseTuple(args, "O", &pyData) == -1)
		{
			PyErr_Format(PyExc_TypeError, "Proxy::streamStringToClient: args is error!");
			PyErr_PrintEx(0);
			return NULL;
		}
	}
	else if(currargsSize == 2)
	{
		if(PyArg_ParseTuple(args, "O|O", &pyData, &pyDesc) == -1)
		{
			PyErr_Format(PyExc_TypeError, "Proxy::streamStringToClient: args is error!");
			PyErr_PrintEx(0);
			return NULL;
		}
	}
	else if(currargsSize == 3)
	{
		if(PyArg_ParseTuple(args, "O|O|H", &pyData, &pyDesc, &id) == -1)
		{
			PyErr_Format(PyExc_TypeError, "Proxy::streamStringToClient: args is error!");
			PyErr_PrintEx(0);
			return NULL;
		}
	}

	char* pDescr = NULL;

	if(pDescr != NULL)
	{
		wchar_t* PyUnicode_AsWideCharStringRet1 = PyUnicode_AsWideCharString(pyDesc, NULL);
		pDescr = strutil::wchar2char(PyUnicode_AsWideCharStringRet1);
		PyMem_Free(PyUnicode_AsWideCharStringRet1);
	}

	if(pDescr && strlen(pDescr) > 255)
	{
		PyErr_Format(PyExc_TypeError, "Proxy::streamFileToClient: the descr-size(%d > 255)!", 
			strlen(pDescr));

		PyErr_PrintEx(0);
		free(pDescr);
		return NULL;
	}

	int16 rid = pobj->streamStringToClient(pyData, 
						(pDescr == NULL ? "" : pDescr),  
						id);

	if(pDescr)
		free(pDescr);

	return PyLong_FromLong(rid);
}