DLLs mit FreeBasic

Dll erstellen und mit AutoIt nutzen – FreeBasic Tutorial

Ich hab hier mal ein rudimentäres Tutorial zusammengeklopft, welches zeigen soll, wie man in FreeBasic eine Dll für AutoIt erstellt.

 

Dieses Tutorial richtet sich in erster Linie an all diejenigen, die mit AutoIt begonnen haben zu programmieren und nun so langsam an die Geschwindigkeitsgrenze von AutoIt stoßen.

 

Ich habe mich für FreeBasic entschieden, weil es Free ist, eine ähnliche Syntax wie AutoIt hat, sehr klein und ohne unnötige Extras daherkommt und bei zahlreichen Tests kleinere und schnellere Dll´s gezaubert hat als andere Compiler.

Wer AutoIt beherscht sollte damit relativ leicht zurechtkommen!

 

 

 

Einrichten von FreeBasic:

 

Zunächst benötigen wir den Compiler, welcher u.a. hier zu finden ist: http://www.freebasic-portal.de/downloads…indows-199.html

Als Editor verwende ich FBEdit: http://www.freebasic-portal.de/downloads…dit-ide-30.html

 

EDIT: Dank BugFix kann man nun auch SciTE als Editor verwenden: FreeBasic läßt sich auch rudimentär in SciTE einbinden

 

 

1) FreeBasic installieren:

Einfach FreeBASIC-0.23.0-win32.exe ausführen und den Anweisungen folgen

 

2) FBEdit.zip in den FreeBasic-Ordner enpacken (z.B.: C:\Programme\FreeBASIC\FbEdit)

 

3) FBEdit starten:

Beim ersten Start muss man die Pfade eingeben:

Compiler Path: C:\Programme\FreeBASIC

Help Path: C:\Programme\FreeBASIC\FbEdit\Help

 

Activate FbEdit Lite for beginners mit "Nein" beantworten.

 

4) Hilfe einrichten:

Um die Hilfe in FbEdit benutzen zu können, muss noch das hier geladen werden: http://www.freebasic-portal.de/downloads…0-23-0-198.html

Nach dem Entpacken in FB.chm umbenennen und in den Hilfe-Ordner kopieren.

Ich selber habe noch "win32.hlp" im Hilfe-Ordner liegen

Diese 4 Hilfen (FB.chm, FbEdit.chm, Windows_Styles.chm u win32.hlp) sind standartmässig bereits eingetragen und können via Options-Help Menu editiert werden

 

 

 

Erstellen einer DLL:

 

1) FbEdit starten

2) File – New Project

3) Project Name und Description eingeben

4) "Project Type" = "Windows dll" auswählen und OK klicken

 

5) Folgenden Code ins Editorfenster eintippen:

 

Code kopieren

Quellcode

1

2

3

4

5

6

7

 

Extern "Windows-MS"

 

Function _Add(iX As Integer, iY As Integer)As Integer Export

Return iX + iY

End Function

 

End Extern

 

6) Make – Compile im Menü aufrufen oder F5 drücken

Fertig ist die erste Dll

 

Zum testen benötigen wir noch ein AutoIt-Script:

AutoIt-QuellcodeCode kopieren

1

2

3

 

$hDll = DllOpen("Add.dll")

$aResult = DllCall($hDll, "int", "_Add", "int", 1234, "int", 1234)

ConsoleWrite("Ergebnis = " & $aResult[0] & @CRLF)

 

 

Kurze Beschreibung der DLL:

Funktionen, welche man mit AutoIt aufrufen möchte, sollten zwischen <Extern "Windows-MS"> und <End Extern> stehen

Dadurch kann man die Funktionen dann mit demselben Namen aufrufen, wie er im Editor auch angegeben ist.

Andernfalls müsste man bei DllCall "_ADD@8" schreiben, und sollte man 3 Parameter übergeben dann: "_ADD@12", bei 4 "_ADD@16" usw…

 

Die Funktion selber sollte eigentlich selbserklärend sein.

Für jeden Parameter und auch den Rückgabewert muss man einen Datentyp angeben (As Integer)

Das "Export" am Ende der Zeile macht die Funktion "nach aussen hin sichtbar" und muss nur für Funktionen angegeben werden, welche man direkt via AutoIt aufrufen möchte.

 

 

 

Parameter können auch ByRef übergeben werden.

Das funktioniert ungefähr so:

 

QuellcodeCode kopieren

1

2

3

4

5

6

7

 

Extern "Windows-MS"

 

Sub _ByRef(iX As Integer, iY As Integer, ByRef iZ As Integer) Export

iZ = iX + iY

End Sub

 

End Extern

 

 

 

 

AutoIt-QuellcodeCode kopieren

1

2

3

 

$hDll = DllOpen("ByRef.dll")

$aResult = DllCall($hDll, "none", "_ByRef", "int", 1234, "int", 1234, "int*", 0)

ConsoleWrite("+ Ergebnis = " & $aResult[3] & @CRLF)

 

 

 

 

 

Hier noch ein kurzes Beispiel, wie man den Inlineassembler von FreeBasic benutzt:

 

QuellcodeCode kopieren

1

2

3

4

5

6

7

8

9

10

11

12

13

14

 

Extern "Windows-MS"

 

Function _ASM_ADD(iX As Integer, iY As Integer)As Integer Export

Dim As Integer iZ

Asm

mov eax, [iX]

mov ebx, [iY]

Add eax, ebx

mov [iZ], eax

End Asm

Return iZ

End Function

 

End Extern

 

 

 

AutoIt-QuellcodeCode kopieren

1

2

3

 

$hDll = DllOpen("ASM.dll")

$aResult = DllCall($hDll, "int", "_ASM_ADD", "int", 1234, "int", 1234)

ConsoleWrite("+ Ergebnis = " & $aResult[0] & @CRLF)

 

 

 

 

 

Verwenden von Arrays:

Um eine große Anzahl von Daten an die Dll zu übergeben bzw. zu erhalten, erstellt man in AutoIt zunächst eine DllStruct und deren Pointer wird an die Dll übergeben.

 

Beispiel:

2 Arrays vom Typ integer und Singlefloat mit jeweils 100 Einträgen werden benötigt:

In AutoIt erstellt man nun eine DllStruct:

AutoIt-QuellcodeCode kopieren

1

 

$tStruct = DllStructCreate("int X[100]; float Y[100];")

 

In FreeBasic muss man zunächst einen Type definieren, damit der Compiler weiß wie die Daten im Speicher liegen:

QuellcodeCode kopieren

1

2

3

4

5

6

 

Type t_Struct

X(1 To 100) As Integer

Y(0 To 99) As Single

End Type

 

Sub _Test(pStruct As t_Struct Ptr)

 

(Hier kann man je nach belieben 1-100 oder 0-99 verwenden)

 

Der Parameter heisst hier pStruct und ist ein Pointer zu einem Speicherbereich in welchem die Daten lt. t_Struct liegen.

 

Wie man nun damit arbeitet, soll folgendes Beispiel zeigen:

 

QuellcodeCode kopieren

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

 

Type t_CircleData

iMX As Integer

iMY As Integer

aX(0 To 359) As Single

aY(0 To 359) As Single

End Type

 

Public Const Pi = 3.14159265358979

Public Const Deg2Rad = Pi / 180

 

Extern "Windows-MS"

 

Sub _Circle(iX As Integer, iY As Integer, iR As Integer, tCirlce As t_CircleData Ptr) Export

Dim As Single fRad

 

For i As UInteger = 0 To 359

fRad = i * Deg2Rad

tCirlce->aX(i) = Cos(fRad) * iR + iX

tCirlce->aY(i) = Sin(fRad) * iR + iY

Next

 

tCirlce->iMX = iX

tCirlce->iMY = iY

End Sub

 

End Extern

 

 

 

AutoIt-QuellcodeCode kopieren

1

2

3

4

5

6

7

8

9

10

11

12

 

$tCircle = DllStructCreate("int iMX; int iMY; float aX[360]; float aY[360];")

$pCircle = DllStructGetPtr($tCircle)

 

$hDll = DllOpen("Array.dll")

DllCall($hDll, "none", "_Circle", "int", 400, "int", 400, "int", 180, "ptr", $pCircle)

 

For $i=1 To 360

   $iX = DllStructGetData($tCircle, "aX", $i)

   $iY = DllStructGetData($tCircle, "aY", $i)

   MouseMove($iX, $iY, 1)

   ConsoleWrite($iX & " " & $iY & @CRLF)

Next

 

 

 

 

Am Schluss noch ein paar Infos:

Wenn man die Datei mit der Endung .fbp mit einem normalen Text-Editor öffnet, dann kann man die Compileroptionen verändern:

Die Zeile sieht in unseren Beispielen so aus:

1=Windows dll,fbc -s gui -dll -export

Wir fügen nun -R hinzu:

1=Windows dll,fbc -s gui -dll -export -R

Wenn wir die Datei nun mit FbEdit öffnen und neu kompilieren, dann entsteht eine neue Datei mit der Endung .asm

Darin finden wir unsere Funktionen als Assembler Code und das kann manchmal ganz nützlich sein.

 

Die Parameter -fpmode FAST -fpu SSE legen in bestimmten Fällen noch den Turbo ein.

Wenn die Dll fertig ist, dann am besten 2mal komiplieren, einmal ohne und einmal mit diesen Parametern; und überprüfen welche Version schneller ist ;)

(bei einer meinen Tests konnte ich so eine Funktion von etwa 600ms auf 450ms beschleunigen)

 

 

 

Das wars für´s Erste mal…

Bei Interesse an weiteren, spezielleren Beispielen (z.B.: Bildbearbeitung) einfach melden.

 

Im Anhang sind noch alle obigen Beispiele als Quallcode und comiliert

 

 

 

EDIT 1

Hier zwei Beispiele für Fortgeschrittene:

 

Anhand eines einfachen Greyscale-Algorithmuses zeige ich hier, wie man in FreeBasic Multithreading realisiert:

 

GreyScale.bas:

 

QuellcodeCode kopieren

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

 

Type t_Param

pPixelData As UInteger Ptr

iPixelCnt As Integer

End Type

 

 

Sub _GreyScaleFunc(pParam As t_Param Ptr)

Dim As UByte Ptr pARGB

Dim As UByte iLuma

 

For i As UInteger = 0 To pParam->iPixelCnt -1

pARGB = @pParam->pPixelData[i]

 

'Luma = BlauAnteil * 0.11 + GrünAnteil * 0.59 + RotAnteil * 0.3

iLuma = (pARGB[0] * 0.11) + (pARGB[1] * 0.59) + (pARGB[2] * 0.3)

 

pARGB[0] = iLuma

pARGB[1] = iLuma

pARGB[2] = iLuma

Next

 

End Sub

 

 

Extern "Windows-MS"

 

Sub _GreyScale(pPixelData As UInteger Ptr, iPixelCnt As Integer) Export

Dim As t_Param tParam(0 To 3)

Dim As Integer iPixel_4 = iPixelCnt / 4

 

'Einer Threadfunktion kann man nur einen Pointer übergeben, deshalb erstellen wir 4 Variablen vom Typ t_Param und befüllen diese mit den entsprechenden Werten

For i As UInteger = 0 To 3

tParam(i).pPixelData = pPixelData + (iPixel_4 * i) ' Startposition des ersten zu berechnenden Pixels

tParam(i).iPixelCnt = iPixel_4 ' Anzahl der Pixel pro Thread

Next

 

Dim As Any Ptr pThread(0 To 3)

For i As Integer = 0 To 3

If i = 2 Then Continue For ' zu Testzwecken: 3 Thread überspringen

pThread(i) = ThreadCreate(@_GreyScaleFunc, @tParam(i)) 'starte Threads

Next

 

For i As Integer = 0 To 3

ThreadWait(pThread(i)) 'warten bis alle Threads fertig

Next

 

End Sub

 

End Extern

 

Und das dazugehörige AutoIt Script zum Testen:

 

AutoIt-QuellcodeCode kopieren

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

 

#include <GDIPlus.au3>

#AutoIt3Wrapper_UseX64=n

 

Global $sPath = FileOpenDialog("open image", "", "(*.jpg;*.bmp;*.png;*.tif;*.gif)")

If @error Or Not FileExists($sPath) Then Exit

 

_GDIPlus_Startup()

 

Global $hImage = _GDIPlus_ImageLoadFromFile($sPath)

Global $aData = _CreatePixelData($hImage)

_GDIPlus_ImageDispose($hImage)

 

 

Global $hDll = DllOpen(@ScriptDir & "\GreyScale.dll")

Global $iTimer = TimerInit()

DllCall($hDll, "none", "_GreyScale", "ptr", $aData[0], "int", $aData[3] * $aData[4])

Global $iTime = TimerDiff($iTimer)

ConsoleWrite(@error & " " & @extended & @CRLF)

 

_GDIPlus_ImageSaveToFile($aData[2], @ScriptDir & "\GreyScale.bmp")

 

_DisposePixelData($aData)

_GDIPlus_Shutdown()

DllClose($hDll)

 

MsgBox(0, "Fertig", "GreyScale fertig in : " & Round($iTime, 3) & "ms" & @CRLF & " 3 Thread wurde übersprungen, deshalb ist das fertige Bild nicht komplett im Grauton!")

ShellExecute(@ScriptDir & "\GreyScale.bmp")

 

 

 

 

 

Func _CreatePixelData($hImage)

   Local $iImgW = _GDIPlus_ImageGetWidth($hImage)

   Local $iImgH = _GDIPlus_ImageGetHeight($hImage)

 

   Local $tPixelData = DllStructCreate("uint[" & $iImgW * $iImgH & "];")

 

   Local $aResult = DllCall($ghGDIPDll, "uint", "GdipCreateBitmapFromScan0", "int", $iImgW, "int", $iImgH, "int", $iImgW * 4, "int", 0x0026200A, "ptr", DllStructGetPtr($tPixelData), "int*", 0)

   If @error Then Return SetError(1, 1, False)

   Local $hBitmap = $aResult[6]

 

   Local $hContext = _GDIPlus_ImageGetGraphicsContext($hBitmap)

   _GDIPlus_GraphicsDrawImageRect($hContext, $hImage, 0, 0, $iImgW, $iImgH)

   _GDIPlus_GraphicsDispose($hContext)

 

   Local $aReturn[5]

   $aReturn[0] = DllStructGetPtr($tPixelData)

   $aReturn[1] = $tPixelData

   $aReturn[2] = $hBitmap

   $aReturn[3] = $iImgW

   $aReturn[4] = $iImgH

 

   Return $aReturn

EndFunc   ;==>_CreatePixelData

 

 

Func _DisposePixelData(ByRef $aData)

   If Not IsArray($aData) Then Return

   _GDIPlus_BitmapDispose($aData[2])

   $aData[1] = 0

   $aData = 0

EndFunc   ;==>_DisposePixelData

 

 

 

Hier derselbe Algo, allerdings in Assembler:

 

QuellcodeCode kopieren

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

 

Sub ASM_GREYSCALE(iAddr As UInteger, iPixels As UInteger)

 

Dim As UInteger iCnt, iMod

iMod = iPixels Mod 4

iCnt = iPixels – iMod

 

Asm

jmp .GS_Start

 

.align 16

_GS_11: .float 0.11, 0.11, 0.11, 0.11

_GS_59: .float 0.59, 0.59, 0.59, 0.59

_GS_3: .float 0.3, 0.3, 0.3, 0.3

_GS_Blue: .long 255, 255, 255, 255

 

.GS_Start:

mov edi,dword[iAddr]             'Startadress Bitmapdata (Pixel)

mov ecx,dword[iCnt]           'number of Pixel

 

movaps xmm7, [_GS_11]

movaps xmm6, [_GS_59]

movaps xmm5, [_GS_3]

movaps xmm4, [_GS_Blue]

 

  .align 16

.GS_Loop:'until ecx=0

 

movdqu xmm0,[edi]'load 4 pixels to xmm0

movdqa xmm3, xmm0'Pixels to xmm3

Pand xmm3, xmm4'And 000000FF

cvtdq2ps xmm3, xmm3'Int To Float

 

movdqa xmm2, xmm0'Pixels to xmm2

PSRLD xmm2, 8'Green

Pand xmm2, xmm4'And 000000FF

cvtdq2ps xmm2, xmm2'Int To Float

 

movdqa xmm1, xmm0'Pixels to xmm1

PSRLD xmm1, 16'Red

Pand xmm1, xmm4'And 000000FF

cvtdq2ps xmm1, xmm1'Int To Float

 

PSRLD xmm0, 24'Alpha

'Pand xmm0, xmm4'And 000000FF

PSLLD xmm0, 24'Alpha

 

'7=0.11 6=0.59 5=0.3 4=BlueMask 3=Blue 2=Green 1=Red 0=Alpha

mulps xmm3, xmm5'Blue * 0.11

mulps xmm2, xmm6'Green * 0.59

mulps xmm1, xmm7'Red * 0.3

 

addps xmm3, xmm2'Blue + Green

addps xmm3, xmm1'BlueGreen + Red

CVTPS2DQ xmm3, xmm3'float to int

Pand xmm3, xmm4'And 000000FF

 

movdqa xmm2, xmm3

PSLLD xmm2, 8

por xmm3, xmm2'Luma to 0000FF00

 

movdqa xmm1, xmm3

PSLLD xmm1, 16

por xmm3, xmm1'Luma to 00FF0000

 

por xmm3, xmm0'Alpha to FF000000

 

 

movdqu [edi], xmm3'write 4 pixels

 

Add edi,16                           'address next pixel: 4 Byte = 1 dword = 1 Pixel

Sub ecx,4                           'counter (next pixel)

 

ja .GS_Loop                              'until ecx=0

 

mov eax, [iMod]'Falls Pixelanzahl nicht durch 4 teilbar, dann hier restliche Pixel berechnen:

cmp eax, 0

je .GS_End

shl eax, 2'mal 4

Add edi, eax'letzter Pixel

Sub edi, 16'minus 4 Pixel

Xor eax, eax'Reset

mov [iMod], eax'Reset iMod

jmp .GS_Loop'Nochmals Loop für die letzten 4 Pixel (evtl. werden Pixel doppelt berechnet, aber der Geschwindigkeitsvorteil überwiegt)

 

.GS_End:

 

End Asm

 

End Sub

 

 

Extern "Windows-MS"

 

Sub _GreyScale(pPixelData As UInteger Ptr, iPixelCnt As Integer) Export

ASM_GREYSCALE(pPixelData, iPixelCnt)

End Sub

 

End Extern

 

AutoIt-QuellcodeCode kopieren

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

 

#include <GDIPlus.au3>

 

Global $sPath = FileOpenDialog("open image", "", "(*.jpg;*.bmp;*.png;*.tif;*.gif)")

If @error Or Not FileExists($sPath) Then Exit

 

_GDIPlus_Startup()

 

Global $hImage = _GDIPlus_ImageLoadFromFile($sPath)

Global $aData = _CreatePixelData($hImage)

_GDIPlus_ImageDispose($hImage)

 

 

Global $hDll = DllOpen(@ScriptDir & "\GreyScale.dll")

Global $iTimer = TimerInit()

DllCall($hDll, "none", "_GreyScale", "ptr", $aData[0], "int", $aData[3] * $aData[4])

Global $iTime = TimerDiff($iTimer)

ConsoleWrite(@error & " " & @extended & @CRLF)

 

_GDIPlus_ImageSaveToFile($aData[2], @ScriptDir & "\GreyScale.bmp")

 

_DisposePixelData($aData)

_GDIPlus_Shutdown()

DllClose($hDll)

 

MsgBox(0, "Fertig", "GreyScale fertig in : " & Round($iTime, 3) & "ms")

ShellExecute(@ScriptDir & "\GreyScale.bmp")

 

 

 

 

 

Func _CreatePixelData($hImage)

   Local $iImgW = _GDIPlus_ImageGetWidth($hImage)

   Local $iImgH = _GDIPlus_ImageGetHeight($hImage)

 

   Local $tPixelData = DllStructCreate("uint[" & $iImgW * $iImgH & "];")

 

   Local $aResult = DllCall($ghGDIPDll, "uint", "GdipCreateBitmapFromScan0", "int", $iImgW, "int", $iImgH, "int", $iImgW * 4, "int", 0x0026200A, "ptr", DllStructGetPtr($tPixelData), "int*", 0)

   If @error Then Return SetError(1, 1, False)

   Local $hBitmap = $aResult[6]

 

   Local $hContext = _GDIPlus_ImageGetGraphicsContext($hBitmap)

   _GDIPlus_GraphicsDrawImageRect($hContext, $hImage, 0, 0, $iImgW, $iImgH)

   _GDIPlus_GraphicsDispose($hContext)

 

   Local $aReturn[5]

   $aReturn[0] = DllStructGetPtr($tPixelData)

   $aReturn[1] = $tPixelData

   $aReturn[2] = $hBitmap

   $aReturn[3] = $iImgW

   $aReturn[4] = $iImgH

 

   Return $aReturn

EndFunc   ;==>_CreatePixelData

 

 

Func _DisposePixelData(ByRef $aData)

   If Not IsArray($aData) Then Return

   _GDIPlus_BitmapDispose($aData[2])

   $aData[1] = 0

   $aData = 0

EndFunc   ;==>_DisposePixelData