toasterking

DllCall Code Generator

14 posts in this topic




Thanks. Works fine for easy DLL calls and is good for beginners. If there are more difficult DLL functions with pointer to structs then it will not work anymore, but it's a good start.


Programming today is a race between software engineers striving to
build bigger and better idiot-proof programs, and the Universe
trying to produce bigger and better idiots.
So far, the Universe is winning.

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

Can't argue with that, I'm sure this will be very useful to a lot of people.

Since your screenshot and link refer to "GetDiskFreeSpace", you probably should start with that in the appropriate input field rather than MessagBox.

Good work.

EDIT:

After trying your linked example "GetDiskFreeSpace" I turned my attentions to "GetDiskFreeSpaceEx" and seen that the PULARGE_INTEGER type is not supported in your early script, I believe it is "uint64*" in AutoIt.

I'm sure there will be more to add if you continue to support the tool.

Edited by JohnOne

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites

Thanks, 

I think it's very handy for me.

1 person likes this

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

J1,

Thanks for your compliments!

Since your screenshot and link refer to "GetDiskFreeSpace", you probably should start with that in the appropriate input field rather than MessagBox.

 

I agree.  I didn't actually mean to leave MessageBoxW as the default field value there.  I was using that for testing and forgot to remove it.  Fixed.

After trying your linked example "GetDiskFreeSpace" I turned my attentions to "GetDiskFreeSpaceEx" and seen that the PULARGE_INTEGER type is not supported in your early script, I believe it is "uint64*" in AutoIt.

 

 

You are correct.  I somehow missed PULARGE_INTEGER, ULARGE_INTEGER, and LARGE_INTEGER in the conversion function.  I added them.  If you enter an unknown MSDN type now, it prompts for the correct AutoIt type in case you are smarter than it is.

Edit:  GetDiskFreeSpaceEx works for me now.

Edited by toasterking

Share this post


Link to post
Share on other sites

Thanks. Works fine for easy DLL calls and is good for beginners. If there are more difficult DLL functions with pointer to structs then it will not work anymore, but it's a good start.

 

Thanks!  It is not complete and it may never be.  But I wanted to put it out there in the hopes that it can benefit someone as-is.

1 person likes this

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

Very nice! Exactly the kind of tool that will come in very handy :)

 

This link is broken:

A great tutorial I used when I was starting to learn this stuff myself is Dealing with DLLs in AutoIt by Andreas Karlsson.  

Edited by Skysnake

Skysnake

Why is the snake in the sky?

Share this post


Link to post
Share on other sites

This link is broken:

Thanks.  I updated the link in the original post with the one Reb provided.

Share this post


Link to post
Share on other sites

Thx.  

I posted something about DllCall in the C# section. Care to take a look.  It is too complex for me and I cant find the corresponding values in the lookup.  I cant do it :(

 


Skysnake

Why is the snake in the sky?

Share this post


Link to post
Share on other sites

Looks good for DllCall beginners =)

Thanks!

But instand of 1000 cases in _ConvertType, why you dont work with arrays?

Mostly for speed.  It's habit; I make optimizations when I see them.  Try this example code.  The same lookup operation takes 3 times as long with an array as with a Switch statement.

My times:
Lookup1 time: 5993.06858483286 ms
Lookup2 time: 15289.7226984924 ms

Global $aLookup[15][2] = [[1,"one"], _
                         [2,"two"], _
                         [3,"three"], _
                         [4,"four"], _
                         [5,"five"], _
                         [6,"six"], _
                         [7,"seven"], _
                         [8,"eight"], _
                         [9,"nine"], _
                         [10,"ten"], _
                         [11,"eleven"], _
                         [12,"twelve"], _
                         [13,"thirteen"], _
                         [14,"fourteen"], _
                         [15,"fifteen"]]

Local $tTest = TimerInit()
For $i = 1 To 1000000
    _Lookup1("fifteen")
Next
ConsoleWrite("Lookup1 time: " & TimerDiff($tTest) & " ms" & @CRLF)

$tTest = TimerInit()
For $i = 1 To 1000000
    _Lookup2("fifteen")
Next
ConsoleWrite("Lookup2 time: " & TimerDiff($tTest) & " ms" & @CRLF)

Func _Lookup1($sName)
    Switch $sName
        Case "one"
            Return 1
        Case "two"
            Return 2
        Case "three"
            Return 3
        Case "four"
            Return 4
        Case "five"
            Return 5
        Case "six"
            Return 6
        Case "seven"
            Return 7
        Case "eight"
            Return 8
        Case "nine"
            Return 9
        Case "ten"
            Return 10
        Case "eleven"
            Return 11
        Case "twelve"
            Return 12
        Case "thirteen"
            Return 13
        Case "fourteen"
            Return 14
        Case "fifteen"
            Return 15
        Case Else
            Return 0
    EndSwitch
EndFunc

Func _Lookup2($sName)
    For $i = 1 To UBound($aLookup) - 1
        If $sName = $aLookup[$i][1] Then Return $aLookup[$i][0]
    Next
    Return 0
EndFunc

If you prefer arrays for readability, you're welcome to rewrite it. :)

 

Share this post


Link to post
Share on other sites

I posted something about DllCall in the C# section. Care to take a look.  It is too complex for me and I cant find the corresponding values in the lookup.  I cant do it :(

Honestly, I probably don't know any more than you.  I stopped when I reached the limit of what this code generator can do because that was all I've needed so far.  If the code generator can't solve it and it's not covered on pages 1 to 8 of the linked PDF, I probably can't do it either.  Good luck, though!

1 person likes this

Share this post


Link to post
Share on other sites

Thank you for the reply. 


Skysnake

Why is the snake in the sky?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Similar Content

    • BigDaddyO
      By BigDaddyO
      I've been working with the Windows Credentials store to store credentials for lots of RDP connections.  I'm also using this code in other scripts to store and retrieve "legacy" credentials for my scripts that have a Save Password checkbox.
      All goes well, until someone requests a button to display a list of all saved credentials.  I found the CredEnumerate call and it looks like it's working but the Target and UserName field that I want is stored inside an array of pointers and I can't figure out how to get data from inside that.  I found a post from 2009 that talks about this, but there was never a solution.
       
      Below are my functions put into an example script.  the _Credentials_Enumerate() is where i'm having problems.   Anybody have some ideas?
      Thanks,
      Mike
       
      ;Credentials Manager #include <array.au3> #include <WinAPI.au3> ;Needed for the _WinAPI_GetLastError() ;------------------------------------------------------------------------ ;----- Add items into the Credentials Store ---------------------------- ;------------------------------------------------------------------------ ;~ _Cred_Add("MyCredStored", "ItsMe", "Secret1", "", 1) ;Add a Local Credentials so we can test the retrieval of a password ;~ $aAddCred = _Cred_Add("MyServer", "Domain\adminAccount", "MyS3cr3+P@ssw0rd") ;Add domain Credentials that can only be used with RDP and other such items ;~ _ArrayDisplay($aAddCred, "AddCred") ;------------------------------------------------------------------------ ;------------------------------------------------------------------------ ;----- Retrieve Credentials from the Credentials Store ----------------- ;------------------------------------------------------------------------ ;~ $aCreds = _Cred_Get("MyServer", 2) ;Retrieve Domain Cred's, won't have password in it ;~ _ArrayDisplay($aCreds, "Credentials") $aCreds = _Credentials_Enumerate() ;Get a list of all credentials currently stored on the system **(DOES NOT WORK)** ;------------------------------------------------------------------------ ;------------------------------------------------------------------------ ;----- Delete a Credential from the Credentials Store ------------------ ;------------------------------------------------------------------------ ;~ _Cred_Delete("MyServer") ;Delete the specified item from the Credential Store ;~ For $d = 1 to UBound($aCreds) - 1 ;~ _Cred_Delete($aCreds[$d][0]) ;Loop to delete all items found. **(DOES NOT WORK)** ;~ Next ;------------------------------------------------------------------------ ;================================================================================================ ;===== Add a Credential into the Credentials Store ============================================= ;================================================================================================ Func _Cred_Add($sTarget, $sUser, $sPassword, $sComm = "", $iType = 2) ;Type: 2=Domain, 1=Local Local $structTarget = DllStructCreate("wchar[100]") ; Create a structure to hold the Target object name DllStructSetData($structTarget, 1, $sTarget) ; Insert the target name into that Structure Local $structUser = DllStructCreate("wchar[100]") ; Create a structure to hold the UserName to use DllStructSetData($structUser, 1, $sUser) ; Insert the user name into the structure Local $structPwd = DllStructCreate("wchar[100]") ; Create a structure to hole the password to use DllStructSetData($structPwd, 1, $sPassword) ; Insert the password into the structure Local $structComment = DllStructCreate("wchar[100]") ; I don't see where this is used, but was in all the examples DllStructSetData($structComment, 1, $sComm) Local $structCREDENTIAL= "" & _ "DWORD Flags;" & _ "DWORD Type;" & _ "Ptr TargetName;" & _ "Ptr Comment;" & _ "UINT64 LastWritten;" & _ "DWORD CredintialBlobSize;" & _ "Ptr CredentialBlob;" & _ "DWORD Persist;" & _ "DWORD AttributeCount;" & _ "ptr Attributes;" & _ "Ptr TargetAlias;" & _ "Ptr Username" Local $NewCred = DllStructCreate($structCREDENTIAL) If @error Then MsgBox(0, "NewCred", "Error in DllStructCreate " & @error); Exit EndIf DllStructSetData($NewCred,"Flags",0) DllStructSetData($NewCred,"Type",$iType) ;2 = Domain, 1 = Generic DllStructSetData($NewCred,"TargetName",DllStructGetPtr($structTarget)) DllStructSetData($NewCred,"Persist",3) DllStructSetData($NewCred,"AttributeCount",0) DllStructSetData($NewCred,"UserName",DllStructGetPtr($structUser)) DllStructSetData($NewCred,"CredentialBlob",DllStructGetPtr($structPwd)) DllStructSetData($NewCred,"CredintialBlobSize",StringLen($sPassword)*2) DllStructSetData($NewCred,"Comment",DllStructGetPtr($structComment)) Local $hAdvapi32 = DllOpen("Advapi32.dll") If $hAdvapi32 = -1 Then Msgbox(0, "Error", "Failed to connect to the Credentials Store") Exit Endif $Ret = DllCall($hAdvapi32, 'bool', 'CredWriteW', 'ptr', DllStructGetPtr($NewCred), 'dword', 0) $NewCred = 0 If IsArray($Ret) Then Return $Ret Else Return SetError(1) EndIf EndFunc ;_Cred_Add ;================================================================================================ ;===== Retrieve the Credentials for the specified item ========================================= ;================================================================================================ Func _Cred_Get($sTarget, $iType = 1) ;Type: 2=Domain, 1=Local. CAN'T RETURN DOMAIN PASSWORDS!!! Local $FuncRet[3] Local $structTarget = DllStructCreate("wchar[100]") DllStructSetData($structTarget,1,$sTarget) Local $hAdvapi32 = DllOpen("Advapi32.dll") If $hAdvapi32 = -1 Then Msgbox(0, "Error", "Failed to connect to the Credentials Store") Exit Endif Local $Ret = DllCall($hAdvapi32, 'bool', 'CredReadW', 'ptr', DllStructGetPtr($structTarget), 'dword', $iType, 'dword', 0, 'ptr*', 0) if $ret[0]=0 then Return SetError(1,0,$FuncRet) Local $structCREDENTIAL= "" & _ "DWORD Flags;" & _ "DWORD Type;" & _ "Ptr TargetName;" & _ "Ptr Comment;" & _ "UINT64 LastWritten;" & _ "DWORD CredintialBlobSize;" & _ "Ptr CredentialBlob;" & _ "DWORD Persist;" & _ "DWORD AttributeCount;" & _ "Ptr Attributes;" & _ "Ptr TargetAlias;" & _ "Ptr Username" Local $tdata=DllStructCreate($structCREDENTIAL, $Ret[4]) Local $userName = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'Username')) Local $User = DllStructGetData($userName, 1) Local $CredentialBlobSize = DllStructGetData($tdata, 'CredintialBlobSize') Local $credentialBlob = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'CredentialBlob')) Local $Password = StringLeft(DllStructGetData($credentialBlob, 1), $CredentialBlobSize/2) Local $Comment = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'Comment')) Local $Comm = DllStructGetData($Comment, 1) Dim $FuncRet[] = [$User, $Password, $Comm] Return $FuncRet EndFunc ;_Cred_Get ;================================================================================================ ;===== Delete a specified item from the Credentials Store ====================================== ;================================================================================================ Func _Cred_Delete($sTarget, $iType = 2) ;Type: 2=Domain, 1=Local Local $structTarget = DllStructCreate("wchar[100]") ;Create a structure to hold the object name we want to delete DllStructSetData($structTarget, 1, $sTarget) ;Insert the Object Name into the Structure Local $hAdvapi32 = DllOpen("Advapi32.dll") If $hAdvapi32 = -1 Then Msgbox(0, "Error", "Failed to connect to the Credentials Store") Exit Endif ;Now send all the info into the DLL to delete the item $Ret = DllCall($hAdvapi32, 'bool', 'CredDeleteW', 'ptr', DllStructGetPtr($structTarget), 'dword', $iType, 'dword', 0) ;$iType 2 = Domain, 1 = Local EndFunc ;_Cred_Delete ;================================================================================================ ;===== Return a 2D array with the Target, UserName, Password for every item ==================== ;===== in the Credentials Store ==================== ;================================================================================================ Func _Credentials_Enumerate() ;https://msdn.microsoft.com/en-us/library/windows/desktop/aa374794(v=vs.85).aspx ;https://www.autoitscript.com/forum/topic/99705-credenumerate-function-call/?do=findComment&comment=715159 Local $aResult Local $structCREDENTIAL = "DWORD Flags;" & _ "DWORD Type;" & _ "Ptr TargetName;" & _ "Ptr Comment;" & _ "UINT64 LastWritten;" & _ "DWORD CredintialBlobSize;" & _ "Ptr CredentialBlob;" & _ "DWORD Persist;" & _ "DWORD AttributeCount;" & _ "Ptr Attributes;" & _ "Ptr TargetAlias;" & _ "Ptr Username" $aResult = DllCall('advapi32.dll', 'int', 'CredEnumerateW', _ ;Call the Unicode version of CredEnumerate 'wstr', Null, _ ;Don't use any filter since I want everything returned 'uint', 1, _ ;1 = CRED_ENUMERATE_ALL_CREDENTIALS 'uint*', '', _ ;Return the Count of all stored credentials 'ptr*', '') ;Returns a pointer to an Array of pointers? If @error Or ($aResult[0] = 0) Then ConsoleWrite('Error: ' & @error & @TAB & 'Extended: ' & @extended & @CRLF) ConsoleWrite(_WinAPI_GetLastError() & @CRLF) ;1168 = Nothing matches the filter, 1312 = no credential set for this user, 1004 = Flag/Filter options are wrong Return SetError(1) EndIf ConsoleWrite("DllCall Returned = " & $aResult[0] & @CRLF & "Credential Count = " & $aResult[3] & @CRLF & "Pointer to Creds Array = " & $aResult[4] & @CRLF) For $c = 2 to $aResult[3] ;Create enough struct for each item in each credential found $structCREDENTIAL &= "DWORD Flags;" & _ "DWORD Type;" & _ "Ptr TargetName;" & _ "Ptr Comment;" & _ "UINT64 LastWritten;" & _ "DWORD CredintialBlobSize;" & _ "Ptr CredentialBlob;" & _ "DWORD Persist;" & _ "DWORD AttributeCount;" & _ "Ptr Attributes;" & _ "Ptr TargetAlias;" & _ "Ptr Username" Next Local $tdata = DllStructCreate($structCREDENTIAL, $aResult[4]) ;Insert all the data from the array of pointers into this struct Local $FullTarget = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'TargetName')) ;Create and Get the array storing TargetName Local $userName = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'Username')) ;Create and Get the array storing Username Local $CredentialBlobSize = DllStructGetData($tdata, 'CredintialBlobSize') ;Get the password blob Local $credentialBlob = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'CredentialBlob')) ;Create and get the password text Local $Comment = DllStructCreate("wchar[100]", DllStructGetData($tdata, 'Comment')) ;Don't see a need for comments ;Retrieve the data For $c = 1 to $aResult[3] Local $Target = DllStructGetData($FullTarget, $c) ;Retrieve the Target Name from the item # Local $User = DllStructGetData($userName, $c) ;Retrieve the User Name from the item # Local $Password = StringLeft(DllStructGetData($credentialBlob, $c), $CredentialBlobSize/2) ;Retrieve the password, Only works for 1, legacy. domain creds will not return passwords Local $Comm = DllStructGetData($Comment, $c) ;Don't need comments but getting it since it's in all the examples ConsoleWrite("Loop = " & $c & ": Target = " & $Target & ": UserName = " & $User & ": Comment = " & $Comm & @CRLF) Next If $aResult[3] > 0 Then $aCreds = DllCall('advapi32.dll', 'none', 'CredFree', 'ptr', $aResult[4]) ;This is just used to release the pointer. Call when done EndIf EndFunc ;_Credentials_Enumerate  
    • luckyluke
      By luckyluke
      Hello,
      Im trying to read the output from CMD using Dllcall, here is my code:
      #include <WinAPI.au3> #include <array.au3> Global Const $STD_OUTPUT_HANDLE = -11 Global Const $_CONSOLE_SCREEN_BUFFER_INFO = _ "struct;int dwSizeX;" & _ "short dwSizeY;" & _ "short dwCursorPositionX;" & _ "short dwCursorPositionY;" & _ "short wAttributes;" & _ "short Left;" & _ "short Top;" & _ "short Right;" & _ "short Bottom;" & _ "short dwMaximumWindowSizeX;" & _ "short dwMaximumWindowSizeY;endstruct" $pCmd = Run( "cmd.exe" ) Sleep(1000) $hCmd = WinGetHandle("") ConsoleWrite('handle:' & $hCmd & @CRLF) $aRet = DllCall("kernel32.dll", "int", "AttachConsole", "dword", $pCmd) ;_ArrayDisplay($aRet) If $aRet[0] <> 0 Then $vHandle_data='' $vHandle='' $vHandle_data = DllStructCreate($_CONSOLE_SCREEN_BUFFER_INFO) ; Screen Buffer structure $aRet1 = DllCall("kernel32.dll", "hwnd", "GetStdHandle", "dword", $STD_OUTPUT_HANDLE) if not @error Then $vHandle = $aRet1[0] $aRet = DllCall("kernel32.dll", "int", "GetConsoleScreenBufferInfo", "hwnd", $vHandle, _ "ptr", $vHandle_data) MsgBox(0, '1',DllStructGetData($vHandle_data, 'dwSizeX') & _WinAPI_GetLastErrorMessage()) EndIf It did not work, i got the message 'The handle is invalid'. Please help?
      Thank you in advance!
    • MazeM
      By MazeM
      Hi
      here's another UDF for the serial port. It is very similar to CommAPI using kernel32.dll, but all code is packed into a single file without any dependencies, not even using WinAPI.au3. It differs from existing UDF that it doesn't allow a timeout when reading, instead it always returns immediately, either with the requested amount ob bytes read or with a failure status. And of course there is a function provided to query the amount of available bytes in the receive buffer. The reason behind this design decision: You can do 1000 other things in the main loop while checking from time to time if enough data bytes arrived. There's no point to block the program waiting for the serial port.
      It is currently a work-in-progress, as I didn't test all functions yet. The code was developed and tested on Windows 7 64 bit.  The ComUDF-Tests.au3 shows some tests and basic usage of the UDF. Maybe there's no reason to use this UDF, given the existence of the others UDFs, but I did it to get to know DllCall better - I use structs no only to pass but also to get data back (I don't use the array returned by DllCall to read that data, unless required). You're welcome to test it on older and newer Windows versions.
      Here's a list of the implemented functions:
      ; _ComListPorts ; _ComOpenPort ; _ComSetTimeouts ; _ComClosePort ; ; _ComSetBreak ; _ComClearBreak ; _ComGetInputcount ; _ComGetOutputcount ; _ComClearOutputBuffer ; _ComClearInputBuffer ; ; _ComSendByte ; _ComReadByte ; _ComSendBinary ; _ComReadBinary ; ; _ComSendChar ; _ComReadChar ; _ComSendCharArray ; _ComReadCharArray ; _ComSendString ; _ComReadString ; ; __ComClearCommError ; __PurgeComm Maze
       
      ComUDF.au3
      ComUDF-Tests.au3
    • astrionn
      By astrionn
      So I had this Idea of creating a tooltip which shows me my ping.
      That itself was made quickly and I thought too add a couple features.
      I want the tooltip background to be a different color depending on the ping. (good ping is green, medium ping is yellow,...)
      So how do I color in a tooltip? google brought me to this: 
       
      where in the comments I found this:
      $s = "LOW" ToolTip($s, 0, 0, "Battery Information");, $icon) $H_TOOLTIP1 = WinGetHandle($s) DllCall("UxTheme.dll", "int", "SetWindowTheme", "hwnd", $H_TOOLTIP1, "wstr", "", "wstr", "") DllCall("user32.dll", "int", "SendMessage", "hwnd", $H_TOOLTIP1, "int", 1043, "int", 2552550, "int", 0) Sleep(1000) Which I then used in my code with different color codes... Trial and Error brought me these that I wanted to use:
       
      The Problem is if I loop through my code it only sets the color for the 1st loop and then sticks to it.
      The real problem is tho that I don't exactly understand the dllcalls... And I guess that's why it isn't working
      So if someone would be so awesome to explain to me how they work, or at least can give me a list of these parameters then I would really appreciate that and learn something new
      Obviously a solution to my problem is awesome aswell ^^
      I run this under Windows 8.1
      There is my code in a paste.
      https://pastebin.com/q525f7mS
    • Leo1906
      By Leo1906
      Hello Guys,
      once aggain I need your help on a DLL Topic
      I need to pass arguments to my function via a structure, because I am limited to only one argument that can be passed.
      But I don't think that thats so important.
      So here's my approach:
      C++ Code (just the important part):
      extern "C" { struct ParamStruct { const char* test1; const char* test2; const char* test3; int size; }; int testFunc(struct ParamStruct * params) { return params->size; } } And thats how I try to call the function using Autoit:
      Local $struct = "struct;char shapefile[128];char output[128];char filename[128];int size;endstruct" Local $tTest = DllStructCreate($struct) DllStructSetData($tTest, "test1", "Bla") DllStructSetData($tTest, "test2", "BlaBla") DllStructSetData($tTest, "test3", "BlaBlaBla") DllStructSetData($tTest, "size", 40) $dll = DLLOpen("myDLL.dll") $ret = DllCall($dll, "int:cdecl", "testFunc", "STRUCT*", DllStructGetPtr($tTest)) MsgBox(0, 0, $ret[0]) DllClose($dll) Just for testing I want the function to just return the integer value in the struct.
      But this aint working. I tested many things, but still I'm not able to get it running. I even don't know if the mistakes are in the C++ code or the Autoit code or both .. I'm not that skilled at C++ and also not that skilled at Autoit DLLCalls :-/
      I would really appreciate some help!
      Kind regards,
      leo