//编译前预处理 
namespace preload {} 
 
::User32 := raw.loadDll("User32.dll");
::Kernel32 := raw.loadDll("Kernel32.dll");
::FILETIME := class{ 
	INT dwLowDateTime ;
	INT dwHighDateTime ;
}
/**intellisense(::)
::User32=@User32.api( "__/*函数名字*/", "int()"); 
::Kernel32=@Kernel32.api( "__/*函数名字*/", "int()"); 
::FILETIME() = FILETIME结构
end intellisense**/

_INVALID_HANDLE_VALUE = topointer(-1)
gcdata = function(t){
	var d = ..raw.malloc(1)
	d@ = t;
	return d;
}
/*intellisense()
gcdata = @ ..gcdata(\n	_gc = function(){\n		io.print("析构函数被调用了")\n	}\n	_topointer = function(){\n	\n	}\n)\n
_INVALID_HANDLE_VALUE = topointer(-1)\n表示无效句柄 
FILETIME() = FILETIME结构
end intellisense*/


/*intellisense()*/  
string.fromto = function(s,cp=65001,tocp=0){
	if(!s){return};
	s = string.toUnicode(s,cp ); 
	return s && string.fromUnicode(s,tocp); 
}

table.new = function(l,v=0){
	var t  = {};
	for(i=1;l)t[i]=v;
	return t;
}

table.toclass = function(t){ 
	return {@(table.ctor(t))};
}

table.count = function(t){
	var i = 0;
	for(k,v in t){i++};
	return i;
} 
/*end intellisense*/

var getLastError = ::Kernel32.api( "GetLastError", "int()"); 
var formatMessage = ::Kernel32.api("FormatMessageA","INT(INT dwFlags,pointer source,INT id,INT lang,str& buf,INT size,pointer &arg )");
lasterr  = function(err,where){
	err := getLastError(); 
	if(err){
		var len,str =  formatMessage( 0x1000 /*_FORMAT_MESSAGE_FROM_SYSTEM*/,null, err,1024/*默认语言*/, 80, 80 );
		return ..string.concat(str,where),err;
	}
} 

//线程库扩展模块;
::WaitForSingleObject := ::Kernel32.api("WaitForSingleObject", "INT(pointer hHandle,INT dwMilliseconds)");
::WaitForMultipleObjects := Kernel32.api("WaitForMultipleObjects", "INT(INT nCount,struct lpHandles,INT bWaitAll,INT dwMilliseconds)");
 
var threadwait = function(bAll, ...){
    var threads = ...;
    if(type(threads)!=type.table)  
    	threads ={...}
    
	var threads_c = raw.toarray( threads ,"pointer" ,"array") 
	var re = WaitForMultipleObjects(#threads,threads_c,bAll, 0xFFFFFFFF  /* Infinite timeout*/);
	select(re) {
		case 258 //WAIT_TIMEOUT 
			return null,"超时" 
		case 0xFFFFFFFF 
			return null,"失败"  
	}
	return re+1;
} 


/*intellisense()*/  
thread.waitAll = function(...){
	return threadwait(1,...);
}
thread.waitOne = function(...){
	return threadwait(0,...);
}
thread.wait  = function(handle,ms=0xFFFFFFFF){
	return WaitForSingleObject(handle,ms);
}
/*end intellisense*/
 
var SetThreadAffinityMask = Kernel32.api("SetThreadAffinityMask","INT( int hThread,INT dwProcessAffinityMask)" )
thread.setAffinity = function( h,cpu = 1){
    SetThreadAffinityMask( h,cpu );
}

/*intellisense()
lasterr() = 返回WINAPI或COM API的最后一次错误信息,第二个返回值为错误码\n无错误则返回null空值
thread.setAffinity(__,2) = 指定线程在哪个CPU上运行
thread.setAffinity(__) = 指定线程在CPU 1上运行 
end intellisense*/

//io.open共享模式参数
 /**intellisense()
_SH_DENYRW=@0x10/*独占读写*/
_SH_DENYWR=@0x20/*独占写*/
_SH_DENYRD=@0x30/*独占读*/
_SH_DENYNO=@0x40/*共享模式*/
_SH_SECURE=@0x80/*安全模式*/
end intellisense**/