MCode4GCC -- C/C++ to MCode Generator

Post your working scripts, libraries and tools for AHK v1.1 and older
SOTE
Posts: 1426
Joined: 15 Jun 2015, 06:21

Re: MCode4GCC -- C/C++ to MCode Generator

13 Dec 2018, 22:12

joedf wrote:
13 Dec 2018, 22:02
well here's what it does currently

Code: Select all

Get_CompilerType(cp) {
	if !FileExist(cp)
		cp:=get_where_Path(cp)
	if Is64BitAssembly(cp)
		return "64"
	else
		return "32"
}
https://github.com/joedf/MCode4GCC/blob ... #L334-L341

But it isnt the most reliable because it seems that some compilers with 32bit exe's to make 64bit exe.... weird :b
I think that I see what you saying, maybe TDM is just weird. The different gcc.exe downloads of MingGW32 and MingGW64 from SourceForge seem to not have any issues, with being properly identified by your program.
User avatar
joedf
Posts: 8940
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

Re: MCode4GCC -- C/C++ to MCode Generator

13 Dec 2018, 23:00

Yeah...
So tested an install, seems like the exe is 32bit, but at least the data from gcc -v mentions x64...

Code: Select all

C:\TDM-GCC-64\bin>gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=C:/TDM-GCC-64/bin/../libexec/gcc/x86_64-w64-mingw32/5.1.0/lto-wrapper.exe
Target: x86_64-w64-mingw32
Configured with: ../../../src/gcc-5.1.0/configure --build=x86_64-w64-mingw32 --enable-targets=all --enable-languages=ada,c,c++,fortran,lto,objc,obj-c++ --enable-libgomp --enable-lto --enable-graphite --enable-cxx-flags=-DWINPTHREAD_STATIC --disable-build-with-cxx --disable-build-poststage1-with-cxx --enable-libstdcxx-debug --enable-threads=posix --enable-version-specific-runtime-libs --enable-fully-dynamic-string --enable-libstdcxx-threads --enable-libstdcxx-time --with-gnu-ld --disable-werror --disable-nls --disable-win32-registry --prefix=/mingw64tdm --with-local-prefix=/mingw64tdm --with-pkgversion=tdm64-1 --with-bugurl=http://tdm-gcc.tdragon.net/bugs
Thread model: posix
gcc version 5.1.0 (tdm64-1)

C:\TDM-GCC-64\bin>
This could work, just more overhead tho...
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]
CyL0N
Posts: 211
Joined: 27 Sep 2018, 09:58

Re: MCode4GCC -- C/C++ to MCode Generator

24 Dec 2018, 06:05

Hey, I thought i'd maybe suggest you add a 'Compile & Execute Selection' hotkey, should make it easier to test...
I just think it's too convenient to have & too trivial not have built in...

Here's my mod... at the very end here. Ctrl+E generates MCode, Executes & returns output using defined return type.

Code: Select all

#NoEnv
#NoTrayIcon
#SingleInstance, Off
SetBatchLines,-1
SetKeyDelay, -1, 0
SetWorkingDir %A_ScriptDir%

MCode4GCC_settings =
(
[settings]
Compilerpath=gcc
StripDebugInfo=1
Optimize=3
MCodeStyle=Bentschi
)
/*
[INICONFIGDefaultEND]
*/
if !FileExist(settings_File:="MCode4GCC.ini")
	FileAppend,%MCode4GCC_settings%,%settings_File%

;=====================[ GLOBAL VARS ]=======================
EnvGet, @PATH_VAR, Path
@REVISION_DATE := "00:25 2015/02/03"
;===========================================================

Menu, FileMenu, Add, &Generate MCode, Generate
Menu, FileMenu, Add
Menu, FileMenu, Add, E&xit`tAlt+F4, GuiClose
Menu, MRefMenu, Add, Bentschi Style, SetMCodeStyle
Menu, MRefMenu, Add, Laszlo Style, SetMCodeStyle
Menu, HelpMenu, Add, Help`tF1, Help
Menu, HelpMenu, Add, MCode &Help (Forum Thread), MCodeHelp
Menu, HelpMenu, Add
Menu, HelpMenu, Add, &About, About
Menu, MenuBar, Add, &File, :FileMenu
Menu, MenuBar, Add, &Settings, :MRefMenu
Menu, MenuBar, Add, &Help, :HelpMenu
Gui, Menu, MenuBar


Gui +hwndhMainGUI
Gui, Font,s12,Arial
Gui, Add, Text, x11 y8,MCode Generator using GCC
Gui, Font
Gui, Add, Text, x11 w520 h2 +0x1007
Gui, Add, GroupBox, x11 w520 h86, Required Parameters
Gui, Add, Text, x24 yp+27, Source (script file)
Gui, Add, Edit, x144 yp-5 w247 h23 +Disabled vSourceFile, `%Clipboard`%
Gui, Add, Button, x398 yp w53 h23 gBrowseSrc, &Browse
Gui, Add, Button, x+4 yp w64 h23 gUseCBoard, Clipboard
Gui, Add, Text, x24 yp+34, GCC Compiler
Gui, Add, Edit, x144 yp-4 w315 h23 vExeFile, % Get_Compiler(settings_File)
Gui, Add, Button, x466 yp w53 h23 gBrowseExe, B&rowse
Gui, Add, GroupBox, x11 w520 h52, Optimizations
Gui, Add, Radio, x24 yp+22 vOptimize1, None
Gui, Add, Radio, x+10 yp vOptimize2, Size (-Os)
Gui, Add, Radio, x+10 yp vOptimize3, Speed (-Ofast)
Gui, Add, Radio, x+10 yp vOptimize4, Overall (-O3)
Gui, Add, Text, x+15 yp w20, and
Gui, Add, Checkbox, x+21 yp vStripDebugInfo, Strip Debug Info (-g0)
Gui, Add, GroupBox, x11 w520 h128, Compiler Log
Gui, Font,, Consolas
Gui, Add, Edit, x20 yp+18 w502 h100p  +BackgroundTrans +c0x1A1A1A +ReadOnly vCompilerLog hwndhCompilerLog,Ready.
Gui, Font
Gui, Add, Button, x11 w120 h28 gGenerate Default, > &Generate MCode <
Gui, Add, Button, x+3 wp hp gCopytoClipboard, Copy to Clipboard
Gui, Add, Edit, x+5 yp+3 w272 h23 +ReadOnly -Multi vResultEdit, [Empty]
Gui, Add, Statusbar,, Ready

GroupAdd, h_gSelf, ahk_id %hMainGUI%

Gui, Show, w542 h400, MCode4GCC -- C/C++ to MCode Generator

;Load settings
	IniRead,MCodeStyle,%settings_File%,settings,MCodeStyle,Bentschi
	Menu, MRefMenu, Check, %MCodeStyle% Style
	IniRead,x,%settings_File%,settings,Optimize,1
	GuiControl,,Optimize%x%,1
	IniRead,x,%settings_File%,settings,StripDebugInfo
	GuiControl,,StripDebugInfo, % !!(x)

LogLn("<Running on: AHK Version " A_AhkVersion " - " (A_IsUnicode ? "Unicode" : "Ansi") " " (A_PtrSize == 4 ? "32" : "64") "bit>")
return


GuiClose:
	Gui,Submit
	IniWrite,%ExeFile%,%settings_File%,settings,Compilerpath
	IniWrite,%StripDebugInfo%,%settings_File%,settings,StripDebugInfo
	gosub,get_optimizations
	IniWrite,%Optimize%,%settings_File%,settings,Optimize
	IniWrite,%MCodeStyle%,%settings_File%,settings,MCodeStyle
ExitApp

SetMCodeStyle:
	Menu, MRefMenu, UnCheck, Bentschi Style
	Menu, MRefMenu, UnCheck, Laszlo Style
	Menu, MRefMenu, Check, %A_ThisMenuItem%
	MCodeStyle:=RegExReplace(A_ThisMenuItem,"\s.*")
return

get_optimizations:
	Gui, Submit, NoHide
	Optimize:=1
	Loop 4
		if (Optimize%A_index%) {
			Optimize:=A_Index
			break
		}
return

BrowseSrc:
	Gui, +OwnDialogs
	FileSelectFile, x, 1,, Open, C/C++ files (*.c; *.cpp)
	if ErrorLevel
		return
	GuiControl,, SourceFile, %x%
return

BrowseExe:
	Gui, +OwnDialogs
	FileSelectFile, x, 1,, Open, Executable files (*.exe)
	if ErrorLevel
		return
	GuiControl,, ExeFile, %x%
return

UseCBoard:
	GuiControl,,SourceFile, `%Clipboard`%
return

CopytoClipboard:
	GuiControlGet,x,,ResultEdit
	if x != [Empty]
	Clipboard:=x
return

#IfWinActive ahk_group h_gSelf
F1::
Help:
	run https://github.com/joedf/MCode4GCC/blob/master/README.md#help
return
#IfWinActive

MCodeHelp:
	if InStr(MCodeStyle,"Laszlo")
		run http://www.autohotkey.com/board/topic/19483-machine-code-functions-bit-wizardry
	else
		run http://ahkscript.org/boards/viewtopic.php?f=7&t=32
return

GuiDropFiles:
	if A_EventInfo > 1
		MsgBox, 48, MCode4GCC - Warning, You cannot drop more than one file into this window!
	SplitPath, A_GuiEvent,,, dropExt
	if dropExt = c
		GuiControl,, SourceFile, %A_GuiEvent%
	else if dropExt = exe
		GuiControl,, ExeFile, %A_GuiEvent%
return

Generate:
	Gui +Disabled
	Gui +OwnDialogs
	Gui, Submit,NoHide
	gosub,get_optimizations

	;get flags
	GuiControlGet,y,,Optimize%Optimize%,Text
	RegexMatch(y,"(\(.*\))",m)
	flags:= SubStr(m1,2,-1) " " ((StripDebugInfo)?"-g0":"")

	LogLn_Clear()
	LogLn("<Generating MCode...>")
	SB_SetText("Generating MCode...")
	QPC(1)
	if (SourceFile=="`%Clipboard`%") {
		y:=get_TempFile() ".c"
		FileAppend,%Clipboard%,%y%
		if ErrorLevel
		{
			LogLn("<ERROR : Could not write Clipboard contents to file!>")
			MsgBox, 16, MCode4GCC - ERROR, Could not write Clipboard contents to file!
			Gui -Disabled
			return
		}
		x:=MCode_Generate(y,ExeFile,flags)
		FileDelete,%y%
	} else {
		x:=MCode_Generate(SourceFile,ExeFile,flags)
	}
	RunTime:=QPC(0)
	if StrLen(x) {
		if InStr(MCodeStyle,"Bentschi") {
			LogLn("<Converting Hexadecimal to Base64...>")
			x := "2,x" (Get_CompilerType(ExeFile)=="32"?"86":"64") ":" Hex2Base64(x)
		}
		y:="Done. Run time: " RunTime " seconds"
		LogLn("<" y ">")
		SB_SetText(y)
		GuiControl,,ResultEdit,% x
	} else {
		y:="<Failure. Errors occurred. Run time: " RunTime " seconds>"
		LogLn(y)
		SB_SetText(y)
		GuiControl,,ResultEdit,[Empty]
	}
	Gui -Disabled
return

About:
GuiControlGet,ExeFile,,ExeFile
if (About_ExeFile!=ExeFile) {
	x:=Trim(Get_stdout(ExeFile " --version"))
	StringReplace,x,x,`n,,All
	StringReplace,x,x,NO`r,NO%A_Space%,All
	StringReplace,x,x,%A_Space%%A_Space%,`n,All
	ExeFile_a:=x
	ExeFile_t:=Get_CompilerType(ExeFile)
	About_ExeFile:=ExeFile
}
MsgBox, 64, About MCode4GCC,
(
MCode4GCC - C/C++ MCode Generator using GCC
Revision: %@REVISION_DATE%

Copyright ©2014-%A_Year% Joe DF ([email protected])
Special thanks to IsNull, fincs, Laszlo, SKAN, Bentschi and kon

Compiler is %ExeFile_t%-bit.
Compiler Path : "%ExeFile%"
%ExeFile_a%
)
return

MCode_Generate(file,cp,flags:="") {
	global @PATH_VAR
	tmpf_a:=get_TempFile()
	tmpf_b:=tmpf_a "_b"
	tmpf_c:=tmpf_a "_c"
	SplitPath, cp,, cpDir
	if !FileExist(cp) {
		cpPath:=get_where_Path(cp)
		SplitPath, cpPath,, cpDir
	}
	EnvSet, Path, %cpDir% ;Update path environment var
	RunWait, %comspec% /c %cp% %flags% -Wa`,-aln="%tmpf_a%" "%file%" -o "%tmpf_b%" 2> "%tmpf_c%",, UseErrorLevel Hide
	cpRunEL:=ErrorLevel, ReturnVar:=""
	EnvSet, Path, %@PATH_VAR% ;Restore env var
	if cpRunEL = ERROR
	{
		LogLn("<Error : Could not launch GCC! @ " """" cp """")
	} else {
		FileRead,data,%tmpf_a%
		FileRead,out,%tmpf_c%
		if StrLen(out:=Trim(out)) {
			StringReplace,out,out,%file%,SOURCEFILE,All
			out:="`n<Stderr output>:`n============================================================`n" out
			LogLn(out "`r============================================================")
			if Instr(out,"WinMain") ;ignore error: "undefined reference to 'WinMain'" or similar
			{
				LogLn("<Error ignored: undefined reference to 'WinMain'>")
				ReturnVar := MCode_Parse(data)
			}
		} else {
			ReturnVar := MCode_Parse(data)
		}
	}
	FileDelete,%tmpf_a%
	FileDelete,%tmpf_b%
	FileDelete,%tmpf_c%
	return ReturnVar
}

MCode_Parse(data,clean:=1) {
	if (clean)
		data:=MCode_ParseClean(data)
	p := 1, m := "", Output := ""
	while p := RegexMatch(data, "`ami)^\s*\d+(\s[\dA-F]{4}\s|\s{6})([\dA-F]+)", m, p + StrLen(m))
		Output .= m2
	return Output
}

MCode_ParseClean(data) {
	ndata:=""
	Loop, Parse, data, `n, `r
	{
		if Instr(A_LoopField,".ident	" """" "GCC: (GNU)")
			return ndata
		ndata .= A_LoopField "`n"
	}
	return ndata
}

Get_Compiler(sfile:="") {
	if !FileExist(sfile)
		sfile:=A_scriptFullPath
	IniRead,x,%sfile%,settings,Compilerpath,!NULL
	if !FileExist(x) and !StrLen(get_where_Path(x))
		return get_where_Path("gcc")
	return x
}

;;;;;;;;;;;;;;;;;;;;; utility functions ;;;;;;;;;;;;;;;;;;;;;
;###########################################################
;{
LogLn(line){
	global
	CompilerLogData .= line "`n"
	GuiControl,,CompilerLog, % CompilerLogData
	CompilerLog_LogLn+=1
	ControlSend,,{PGDN %CompilerLog_LogLn%}{Down 8}{End},ahk_id %hCompilerLog%
}
LogLn_Clear(){
	global
	CompilerLogData := ""
	GuiControl,,CompilerLog, % CompilerLogData
	CompilerLog_LogLn:=0
	ControlSend,,{PGDN}{Down}{End},ahk_id %hCompilerLog%
}
QPC( R := 0 ) {    ; By SKAN,  http://goo.gl/nf7O4G,  CD:01/Sep/2014 | MD:01/Sep/2014
	Static P := 0,  F := 0,     Q := DllCall( "QueryPerformanceFrequency", "Int64P",F )
	Return ! DllCall( "QueryPerformanceCounter","Int64P",Q ) + ( R ? (P:=Q)/F : (Q-P)/F )
}
get_TempFile(d:="") {
	if ( !StrLen(d) || !FileExist(d) )
		d:=A_Temp
	Loop
		tempName := d "\~temp" A_TickCount ".tmp"
	until !FileExist(tempName)
	return tempName
}
Get_CompilerType(cp) {
	if !FileExist(cp)
		cp:=get_where_Path(cp)
	if Is64BitAssembly(cp)
		return "64"
	else
		return "32"
}
get_where_Path(item) {
	data:=Get_stdout("where " item)
	Loop, parse, data, `n, `r
		return A_loopField	
}
Get_stdout(command) {
	tmpf:=get_TempFile()
	RunWait, %comspec% /c %command% > "%tmpf%",,Hide
	FileRead,data,%tmpf%
	FileDelete,%tmpf%
	return data
}
Is64BitAssembly(appName){
	static GetBinaryType := "GetBinaryType" (A_IsUnicode ? "W" : "A")
	static SCS_32BIT_BINARY := 0
	static SCS_64BIT_BINARY := 6
	ret := DllCall(GetBinaryType
		,"Str", appName
		,"int*", binaryType)
	return binaryType == SCS_64BIT_BINARY
}
Hex2Base64(hex) {
	sz:=StringToBinary(b,hex)
	Base64enc(out,b,sz)
	VarSetCapacity(out,-1) ; Strip everything after first null byte
	;return SubStr(out,1,sz) ; Strip garbage at the end
	return out
}
;http://www.autohotkey.com/board/topic/85709-base64enc-base64dec-base64-encoder-decoder/
Base64enc( ByRef OutData, ByRef InData, InDataLen ) { ; by SKAN
	DllCall("Crypt32.dll\CryptBinaryToString" (A_IsUnicode?"W":"A")
		,UInt,&InData,UInt,InDataLen,UInt,1,UInt,0,UIntP,TChars,"CDECL Int")
	VarSetCapacity(OutData,Req:=TChars*(A_IsUnicode?2:1))
	DllCall("Crypt32.dll\CryptBinaryToString" (A_IsUnicode?"W":"A")
		,UInt,&InData,UInt,InDataLen,UInt,1,Str,OutData,UIntP,Req,"CDECL Int")
	Return TChars
}
; BinaryToString() / StringToBinary() from laszlo, updated by joedf
; http://ahkscript.org/forum/viewtopic.php?p=304556#304556
; fmt = 1:base64, 4:hex-table, 5:hex+ASCII, 10:offs+hex, 11:offs+hex+ASCII, 12:raw-hex
StringToBinary(ByRef bin, hex, fmt=12) {    ; return length, result in bin
	DllCall("Crypt32.dll\CryptStringToBinary","Str",hex,"UInt",StrLen(hex),"UInt",fmt,"UInt",0,"UInt*",cp,"UInt",0,"UInt",0,"CDECL UInt") ; get size
	VarSetCapacity(bin,cp)
	DllCall("Crypt32.dll\CryptStringToBinary","Str",hex,"UInt",StrLen(hex),"UInt",fmt,"UInt",&bin,"UInt*",cp,"UInt",0,"UInt",0,"CDECL UInt")
	Return cp
} 
;}

;SCRIPT END
^e::
cBackup := Clipboardall
WinGet, activeId, ID, A	;so as to not loose focus from working window,by restoring it after compilation..
Send {Ctrl down}c{Ctrl up}
ClipWait, 5
Gosub, Generate
GuiControlGet,x,,ResultEdit
if (x = "[Empty]"){
	SoundPlay,*16,1
	Clipboard := cBackup
	Return
}
InputBox, dType, Input Type, MCode Function Return Type:, , 214, 126, , , , , % dType ? dType : "UInt64" 	;remember last input
mcodeExecFunc=
(
MCode(mcode) {
	static e := {1:4, 2:1}, c := (A_PtrSize=8) ? "x64" : "x86"
	if (!regexmatch(mcode, "^([0-9]+),(" c ":|.*?," c ":)([^,]+)", m))
		return
	if (!DllCall("crypt32\CryptStringToBinary", "str", m3, "uint", 0, "uint", e[m1], "ptr", 0, "uint*", s, "ptr", 0, "ptr", 0))
		return
	p := DllCall("GlobalAlloc", "uint", 0, "ptr", s, "ptr")
	if (c="x64")
		DllCall("VirtualProtect", "ptr", p, "ptr", s, "uint", 0x40, "uint*", op)
	if (DllCall("crypt32\CryptStringToBinary", "str", m3, "uint", 0, "uint", e[m1], "ptr", p, "uint*", s, "ptr", 0, "ptr", 0))
		return p
	DllCall("GlobalFree", "ptr", p)
}
)
mcodeFunc := StrReplace(StrReplace(x,"`n"),"`r")
execFunc := clipboard := "SoundPlay,*-1,1`nMsgbox `% DllCall(MCode(" Chr(0x22) mcodeFunc Chr(0x22) "),""cdecl " dType """)`n" mcodeExecFunc
shell := ComObjCreate("WScript.Shell")
exec := shell.Exec("AutoHotkey.exe /ErrorStdOut *"), exec.StdIn.Write(execFunc), exec.StdIn.Close()
WinActivate, ahk_id %activeId%	;restore working window..
Return

Cheers, happy holidays. :xmas:
live ? long & prosper : regards
User avatar
joedf
Posts: 8940
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

Re: MCode4GCC -- C/C++ to MCode Generator

24 Dec 2018, 23:48

So you would have MCode4GCC simply run in the background?
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]
CyL0N
Posts: 211
Joined: 27 Sep 2018, 09:58

Re: MCode4GCC -- C/C++ to MCode Generator

25 Dec 2018, 03:20

Certainly not, I'd rather it be augmented with a single press 'compile & run' hotkey though... something like 'build & run' in every IDE. It makes for 'not as frustrating' test sessions.
live ? long & prosper : regards
User avatar
joedf
Posts: 8940
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

Re: MCode4GCC -- C/C++ to MCode Generator

25 Dec 2018, 19:40

Hmm, what if I add it as a command line option so it can be easily integrated into an ide?
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]
CyL0N
Posts: 211
Joined: 27 Sep 2018, 09:58

Re: MCode4GCC -- C/C++ to MCode Generator

25 Dec 2018, 20:08

Yes Please. Thanks. :D
live ? long & prosper : regards
SteaIthe
Posts: 10
Joined: 03 Jan 2019, 18:55

Re: MCode4GCC -- C/C++ to MCode Generator

17 Jan 2019, 10:25

Been trying to get this to work but I think I cant find the proper exe in gcc so it keeps erroring out.

I'm really just trying to find a machine code version of ahk's "if var between low and high","ifgreater" amd "ifless"

I'm using these statements 1 time for each seperate r,g and b of every pixel of a bitmap so on a 400x400 bitmap it has to use them 480,000 times and these if statements are slowing it way down.Ive tested and without them the speed goes up by around 500% but I have to have them.
User avatar
joedf
Posts: 8940
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

Re: MCode4GCC -- C/C++ to MCode Generator

19 Jan 2019, 14:00

Could you share these errors? Screenshot or copy text?
Share your code?
Did you install TDM GCC or MinGW GCC? 64 or 32 bit?
What path are you giving MCode4GCC?
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]
SteaIthe
Posts: 10
Joined: 03 Jan 2019, 18:55

Re: MCode4GCC -- C/C++ to MCode Generator

21 Jan 2019, 11:38

Thank you for replying and mostly thanks for the work on this very valuable tool and hope you continue to progress it.
I did end up getting it to work after reading a guide you linked.It actually turned out to be working all along but I was mistaking it for erroring out because the generator was showing:
C:/crossdev/src/mingw-w64-v4-git/mingw-w64-crt/crt/crt0_c.c:18: undefined reference to `WinMain'
collect2.exe: error: ld returned 1 exit status

============================================================
<Error ignored: undefined reference to 'WinMain'>
<Converting Hexadecimal to Base64...>
<Done. Run time: 0.098632 seconds>
I seen the errors and assumed it didn't work even though it generated mcode. However after using the mcode I found that the code was good even with the error.

I did end up finding the type of c code I would need.Something like this
unsigned int MyFunction(unsigned int a,unsigned int b)
{
if (a>0)
return 0;
else
return 1;
}
That would work to replace ahk's conditional statements however I found that the DLL call to the function every time will actually make it a little slower then using ahk's conditional statements so I believe I will try to add the entire loops code into the function that way I only need to make 1 DLL call but due to my lack of coding knowledge of c++ it would be too complicated.

The code is for a tool I made to constantly capture gdi+ bitmaps of an object on the screen,find the lowest and highest intensity of the r,g and b of every pixel of the image from when you began the scan to when you stopped it,calculate the middle intensity of each color of each pixel and remake the bitmap with the those colors that way to make as perfect as possible snippet for image search which I posted here
https://www.autohotkey.com/boards/viewtopic.php?t=60645
User avatar
joedf
Posts: 8940
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

Re: MCode4GCC -- C/C++ to MCode Generator

24 Jan 2019, 15:59

Yeah that error is normal.
Glad to hear it's working now! :+1:
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]
serg
Posts: 56
Joined: 21 Mar 2015, 05:33

Re: MCode4GCC -- C/C++ to MCode Generator

06 Jun 2019, 16:50

Hi Joedf
I just figured out how to use your MCode4GCC, thanks for making it!

There are few small issues with it thou:

1) It didn't work on my 64 computer until I changed 64/32 results in Get_CompilerType(cp), probably Is64BitAssembly(cp) doesnt work properly

2) It works with MinGW, but doesnt with TDM-GCC (both 32 and 64), it returns error (even thou I manually select gcc.exe/g++.exe files):

Code: Select all

gcc.exe: error: CreateProcess: No such file or directory
3) "Speed" optimization returns error "invalid option argument `-Ofast'"

Best regards
User avatar
joedf
Posts: 8940
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

Re: MCode4GCC -- C/C++ to MCode Generator

07 Jun 2019, 09:03

It could be from updates to the different software... a windows function could have gotten changed or something... GCC... it's been a while... I'll take a look. Thanks for reporting :+1:
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]
User avatar
joedf
Posts: 8940
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

Re: MCode4GCC -- C/C++ to MCode Generator

07 Jun 2019, 10:11

Okay... weird I just tested with tdm64-gcc-5.1.0-2... and no issues at all... :think:
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]
serg
Posts: 56
Joined: 21 Mar 2015, 05:33

Re: MCode4GCC -- C/C++ to MCode Generator

07 Jun 2019, 10:28

Hi Joedf, could you please tell me what Im doing wrong here:
Simple C function like "return 42" compiles with MCode4GCC+MinGW and returns correct result (42) just fine. Also when I use machine code from your examples (like "2,x64:M8A4AXQKSP/B/8CAOQB19vPD" for string length), MCode() func also returns correct answer.
BUT when I get MCode (using g++ or gcc.exe from MinGW) for this function:

Code: Select all

int func(int a, int b)
{
  return a+b;
}
and plug it ("2,x64:VYnli0UMA0UIXcOQ") into:

Code: Select all

Msgbox % DllCall(MCode("2,x64:VYnli0UMA0UIXcOQ"),"int",3,"int",2,"cdecl")
it returns "1074464882", i.e. completely wrong result. It also shows some errors

Code: Select all

C:\MinGW\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: /mingw/lib/libmingwex.a(glob.o):(.text+0x9e7): undefined reference to `__chkstk_ms'
C:\MinGW\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: /mingw/lib/libmingwex.a(glob.o):(.text+0xdb2): more undefined references to `__chkstk_ms' follow
collect2: ld returned 1 exit status

============================================================
<Error ignored: undefined reference to 'WinMain'>
<Converting Hexadecimal to Base64...>
<Done. Run time: 0.303631 seconds>
Could you please tell me what's wrong here?
Is error "undefined reference to `__chkstk_ms' / to 'WinMain'" causing this or something else?
I run AHK Unicode 1.1.30.03 on Win8.1 64
serg
Posts: 56
Joined: 21 Mar 2015, 05:33

Re: MCode4GCC -- C/C++ to MCode Generator

07 Jun 2019, 10:38

joedf wrote:
07 Jun 2019, 10:11
Okay... weird I just tested with tdm64-gcc-5.1.0-2... and no issues at all... :think:
When you select compiler (with tdm64-gcc), what file and in what folder do you select?
When I select C:\TDM-GCC-64\bin\g++.exe (or gcc.exe or x86_64-w64-mingw32-g++.exe), error log tells me that g++.exe: error: CreateProcess: No such file or directory

I installed very basic (minimalist) setup of TDM-GCC, maybe that's the problem
User avatar
joedf
Posts: 8940
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

Re: MCode4GCC -- C/C++ to MCode Generator

07 Jun 2019, 13:38

Hmmm... I do full installation, not sure what Those errors are... you seem to be doing everything correctly, except don’t use g++.

I’ll test your mcode and edit this post.

EDIT:

Code: Select all

Msgbox % DllCall(MCode("2,x64:VYnli0UMA0UIXcOQ"),"int",3,"int",2,"cdecl")
Msgbox % DllCall(MCode("2,x86:jQQRw5CQkJCQkJCQkJCQkA=="),"int",3,"int",2,"cdecl")
Hmm weird, first one is blank and the second gives me 9363843... :crazy:
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]
serg
Posts: 56
Joined: 21 Mar 2015, 05:33

Re: MCode4GCC -- C/C++ to MCode Generator

08 Jun 2019, 07:12

Thanks for reply Joedf,
I installed more blocks for MinGW and TDM, MinGW still refuses to work, but TDM finally works! :=)
May I ask you few more things (forgive me if questions are stupid, my level of knowledge here is quite low):

1) Is it possible to convert float/double functions to MCode using your generator? I tried but couldn't get it to work. Maybe need to use some special options with the compiler?
2) When compiler returns Hex number (before converting to Base64) with bunch of "90"s in the end, is it always safe to trim them?
3) And I'm also curious why did you say not to use g++.exe?

Thanks again!
Helgef
Posts: 4709
Joined: 17 Jul 2016, 01:02
Contact:

Re: MCode4GCC -- C/C++ to MCode Generator

08 Jun 2019, 07:33

@serg, hi,
1) :arrow: machine code alway return -0.00000
2) 90's are nops (no operation), if they are trailing they do not pad anything, so you can remove them.

Cheers.
serg
Posts: 56
Joined: 21 Mar 2015, 05:33

Re: MCode4GCC -- C/C++ to MCode Generator

08 Jun 2019, 07:45

I got resulting machine code that is very slow compared to regular AHK code
For example:

Code: Select all

q1 := 3 , q2 := 2

a := A_TickCount
Loop 1000
 q := DllCall(MCode("2,x64:icgPr8LD"),"int",q1,"int",q2,"cdecl")	; "2,x64:icgPr8LD" = q1*q2
a := A_TickCount-a
msgbox %a% ms`n`nAnswer: %q%

a := A_TickCount
Loop 1000
 q := q1*q2
a := A_TickCount-a
msgbox %a% ms`n`nAnswer: %q%
Regular AHK code is much much faster here. Isn't MCode supposed to be super fast? or a function needs to be complex enough for MCode to be faster than regular AHK code? :wtf:

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: No registered users and 109 guests