Jump to content

Understanding DllCall and data types

Recommended Posts

Hi !
I have difficulties to learn how to use WinAPI functions with DllCall.
I red the (very good) >Tutorial on DllCall() & DllStructs. I understand the tutorial, but it's hard for me to apply it myself.
For example, the function GetUserName (just an example, I know @username of course) :

  _Out_    LPTSTR lpBuffer,
  _Inout_  LPDWORD lpnSize


lpBuffer [out]

    A pointer to the buffer to receive the user's logon name. If this buffer is not large enough to contain the entire user name, the function fails. A buffer size of (UNLEN + 1) characters will hold the maximum length user name including the terminating null character. UNLEN is defined in Lmcons.h.
lpnSize [in, out]

    On input, this variable specifies the size of the lpBuffer buffer, in TCHARs. On output, the variable receives the number of TCHARs copied to the buffer, including the terminating null character.

    If lpBuffer is too small, the function fails and GetLastError returns ERROR_INSUFFICIENT_BUFFER. This parameter receives the required buffer size, including the terminating null character.

For me, the first parameter (lpBuffer) sould be a STR type (from AutoIt helpfile in DllCall)

The second, a DWORD (I think), but the MSDN says it is the size of the lpBuffer, in TCHARs : what is it ?

In >this topic, I found a solution for GetUserName :

MsgBox(0, "", _GetUserName() )

Func _GetUserName()
    Local $tlpnSize = DllStructCreate("dword[255]")
    Local $aDLL = DllCall("Advapi32.dll", "int", "GetUserName", "str", "", "dword*", DllStructGetPtr($tlpnSize))
    If @error Then Return SetError(@error, 0, 0)
    Return $aDLL[1]

I don't understand :

 - why using "int" instead of "bool" for the first parameter (as said in the MSDN page)?

 - why the second parameter value is empty ?

 - does TCHAR is equals to dword[255], how to find this by myself ?

 - why the last parameter is not DllStructGetPtr (I thought the size of the lpBuffer buffer should have been defined by DllStructGetSize)

As you can see, I am a newbie for this, and I would like to understand more, but I don't know how ....

Can someone give me some explanations or links ??

Thanks in advance, and sorry for the blurred question...

Share this post

Link to post
Share on other sites

I would write the same function this way, the more right way:

Func _GetUserNameFunkey()
    Local $aDLL = DllCall("Advapi32.dll", "BOOL", "GetUserName", "str", "", "dword*", 255)
    If @error Then Return SetError(@error, 0, 0)
    Return $aDLL[1]

BOOL and int are both 32 bit integer, so it can be interchanged, but for understanding of the function use BOOL so that you know there are only two values returned, zero and non zero.

If you pass an empty string to the dll function then this happens lieke documentation says: a minimum of 65536 chars is allocated.

So the last parameter can be up to 65536 without any difference. But usernames are not that long ;)

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

Thanks for this explanation Funkey. I appreciate you help.

Now, can you explain me how to represent the EXTENDED_NAME_FORMAT parameter in GetUserNameEx function ?

I tried this, but it does not work at all... :

MsgBox(0, "", _GetUserNameEx() )

Func _GetUserNameEx()
    Local $aDLL = DllCall("Secur32.dll", "bool", "GetUserNameEx", "int", 2, "str", "", "ulong*", 255)
    If @error Then Return SetError(@error, 0, 0)
    Return $aDLL[1]
do not laugh, please ... :muttley:

Share this post

Link to post
Share on other sites

Allright JFX !

I begin to understand : $aDLL[1] contains the value of the first parameter (value=2), $aDLL[2] contains the value of the 2nd parameter and so on...
It is written in the helpfile, but I did not understand that.
Thanks, it's clearing up !
I will continue with other functions and come here to ask for help (I will need, sure)
Global Const $NameUnknown = 0, _
             $NameFullyQualifiedDN  = 1, _
             $NameSamCompatible     = 2, _
             $NameDisplay           = 3, _
             $NameUniqueId          = 6, _
             $NameCanonical         = 7, _
             $NameUserPrincipal     = 8, _
             $NameCanonicalEx       = 9, _
             $NameServicePrincipal  = 10, _
             $NameDnsDomain         = 12
MsgBox(0, "", _GetUserNameEx($NameDisplay) )

Func _GetUserNameEx ($NameFormat)
    $ret = DllCall("Secur32.dll", "bool", "GetUserNameEx", "int", $NameFormat , "str", "", "ulong*", 255)
    If @error Then Return SetError(1, 0, 0)
    Return $ret[2]

Share this post

Link to post
Share on other sites

Well, now, I tried to use CreateProfile, and... it's a success !

MsgBox(0, "", _WinAPI_CreateProfile("S-1-5-21-3114055946-370887941-3244374214-500", "administrator") )

Func _WinAPI_CreateProfile($sUserSid, $sUserName)
    Local $ret = DllCall("Userenv.dll", "long", "CreateProfile", "wstr", $sUserSid, "wstr", $sUserName, "wstr", "", "dword", 255)
    If @error Then Return SetError(1, 0, -1)
    Return $ret[3]

i still have difficulties to understand when I must use (or not) a wildcard after the datatype...

Share this post

Link to post
Share on other sites

Thanks trancexx.
Not familiar at all... I have never use C or C++...
It seems to be a reason to my difficulties.

I think there are a lot of members in this case.
What could you recommend to us ? Is it possible to learn how to use complex WinApi funtions with these limited knowledges?

Thanks for your patience

Edited by jguinch

Share this post

Link to post
Share on other sites

You just need to see Conversions from Windows API types to AutoIt types.

it says 


or get the pointer (ptr*) to that unicodestring and supply that pointer to a structure (dllstructcreate("wchar",yourptr)).


PD: I know basic about C++/C


Edited by Danyfirex

Share this post

Link to post
Share on other sites

Hi again !

I tried some other functions, and now I have a little question.

Here is my code for QueryFullProcessImageName (just for learning, I know _WinAPI_GetProcessFileName):

$h = _OpenProcess( @AutoitPid)
MsgBox(0, "", _QueryFullProcessImageName($h) )

Func _QueryFullProcessImageName($hProcess)
    $ret = DllCall("Kernel32.dll", "bool", "QueryFullProcessImageName", "handle", $hProcess, "dword", 0, "str", "", "dword*", 256)
    If @error Then Return SetError(1, 0, -1)
    Return $ret[3]

Func _OpenProcess($iProcessId)
    $ret = DllCall("Kernel32.dll", "HANDLE", "OpenProcess", "dword", 0x0400, "bool", True, "dword", $iProcessId)
    Return $ret[0]

As you can see in my QueryFullProcessImageName call, I set the last parameter to 256. But if the returned full path length is bigger than this value, the function fails.

So my question is : which value should I use for this parameter ? Something like 4096 or more ?

Thanks again. It''s a pleasure to learn with you ! :thumbsup:


Edit : Danyfirex, I do not really understand what you said...

Edited by jguinch

Share this post

Link to post
Share on other sites

If you use (ANSI) API  Use 256.

if you use (Unicode) API use  32767

what exactly you don't understand?


Edited by Danyfirex

Share this post

Link to post
Share on other sites

In this case you have to do the structure before because is not a pointer to constant(LPCSTR/LPCWSTR). and pass the pointer. look:

MsgBox(0, "", _WinAPI_CreateProfile("S-1-5-21-3114055946-370887941-3244374214-500", "Danyfirex") )

Func _WinAPI_CreateProfile($sUserSid, $sUserName)
Local $tPath=DllStructCreate("wchar[255]")
    Local $ret = DllCall("Userenv.dll", "long", "CreateProfile", "wstr", $sUserSid, "wstr", $sUserName, "ptr", DllStructGetPtr($tPath), "dword", 255)
    If @error Then Return SetError(1, 0, -1)
    Return DllStructGetData($tPath,1)

If it was a pointer to a constant you could use ptr* something like this:

;this code will not work (it's a way if the api returns a pointer, CreateProfile does not).

msdn say:

pszProfilePath [out]

When this function returns, contains a pointer to the full path of the profile.

But it's wrong it will need a wide string pointer to fill it.

MsgBox(0, "", _WinAPI_CreateProfile("S-1-5-21-3114055946-370887941-3244374214-521", "Danyfirex") )

Func _WinAPI_CreateProfile($sUserSid, $sUserName)
    Local $tPath=0
    Local $ret = DllCall("Userenv.dll", "long", "CreateProfile", "wstr", $sUserSid, "wstr", $sUserName, "ptr*", 0, "dword", 255)
    If @error Then Return SetError(1, 0, -1)
    Return DllStructGetData($tPath,1)

or simply use Conversions from Windows API types to AutoIt types


Edited by Danyfirex

Share this post

Link to post
Share on other sites

You exactly point out a difficulty for me : wchar[255] in a structure is equivalent to wstr ?

Sorry for these ridiculous questions....

Moderators, if you consider this topic is not in the good section, you can move it. The problem is that I have not just one question, but a lot of interrogations..

Thanks again Danyfirex.

Share this post

Link to post
Share on other sites

Basically yes.

wstr is a pointer to a sequence of Unicode characters with null termination( in this case for being a wide(unicode) string need to be double null termination)

wchar is a sequence of Unicode characters.

if you do a structure with wchar[n size] and pass its pointer is  same as you pass wstr.


Share this post

Link to post
Share on other sites

wchar is the type of one UTF16 (-LE or BE) Unicode encoding unit. A Unicode character needs one or two encoding unit(s) to represent. Those Unicode characters requiring two units are seldom used and AFAIK no widespread font can display them.

So most practical applications restrict wchar to mean "one Unicode character", which implies that only those in BMP (or plane 0 or base Multilingual plane) can be represented. This restricted character set is (roughly) called UCS-2 and it's what AutoIt uses.

wchar is to wstr what char is to str. [w]str is a pointer to the base address of a C [w]char array (C doesn't have a built-in string type).

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

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

    • By Sori
      Not going to dump the code down because it's essentially a keylogger.
    • By TheDcoder
      Hi, I thought I would never post a C/WinAPI related question in this forum ever, but here we are after a few years and me having learnt enough of C to write a basic console program
      My issue is that I am trying to read my child process's stdout output but ReadFile never returns if the child exits or if it is killed... very strange , I have been trying to work my way around this. The options I can think of are:
      Create a new thread and check for existance of the process constantly while reading Somehow make the pipe asynchronous (overlapped) so that I can read it in a non-blocking manner Fix ReadFile to return when the process ends Obviously I would prefer No. 3, I just want to make my program work. Here is my code if you guys want to take a look:
      // No text highlighting for C/C++ but we have it for C#? Blasphemy! bool allium_start(struct TorInstance *instance, char *config, allium_pipe *output_pipes) { char *cmd; // Figure out the command string for execution if (config) { char *parameters = " -f -"; cmd = malloc(strlen(instance->tor_path) + strlen(parameters) + 1); if (!cmd) return false; strcpy(cmd, instance->tor_path); strcat(cmd, parameters); } else cmd = instance->tor_path; // Prepare startup info with appropriate information SecureZeroMemory(&instance->startup_info, sizeof instance->startup_info); instance->startup_info.dwFlags = STARTF_USESTDHANDLES; SECURITY_ATTRIBUTES pipe_secu_attribs = {sizeof(SECURITY_ATTRIBUTES), NULL, true}; HANDLE pipes[2]; if (output_pipes == NULL) { CreatePipe(&pipes[0], &pipes[1], &pipe_secu_attribs, 0); output_pipes = pipes; } instance->startup_info.hStdOutput = output_pipes[1]; instance->startup_info.hStdError = output_pipes[1]; instance->stdout_pipe = output_pipes[0]; // Stored for internal reference if (config) { // Reuse the pipes array to store standard input pipes CreatePipe(&pipes[0], &pipes[1], &pipe_secu_attribs, 0); instance->startup_info.hStdInput = pipes[0]; } // Create the process bool success = CreateProcessA( NULL, cmd, NULL, NULL, config ? true : false, 0, NULL, NULL, &instance->startup_info, SecureZeroMemory(&instance->process, sizeof instance->process) ); // Free command string if needed if (config) free(cmd); // Write config to Tor's standard input unsigned long bytes_written; if (success) { WriteFile(pipes[1], config, strlen(config), &bytes_written, NULL); // Work around for simulating Ctrl + Z which sends the substitution character (ASCII 26), // this is needed in order for Tor to detect EOT/EOF while reading the config WriteFile(pipes[1], &(char){26}, 1, &bytes_written, NULL); } CloseHandle(pipes[1]); // Return on failure if (!success) return false; } char *allium_read_stdout_line(struct TorInstance *instance) { char *buffer = instance->buffer.data; // Check for valid buffer and allocate if needed if (instance->buffer.size == 0 || !buffer) { buffer = instance->buffer.data = malloc(instance->buffer.size = 80 + 1); if (!buffer) return NULL; } // Process the input unsigned int read_len = 0; while (true) { // Read data unsigned long bytes_read; if (ReadFile(instance->stdout_pipe, buffer, 1, &bytes_read, NULL) == false || bytes_read == 0) return NULL; // Check if we have reached end of line if (buffer[0] == '\n') break; // Proceed to the next character ++buffer; ++read_len; // Resize buffer if it is full if (read_len == instance->buffer.size) { char *new_buffer = malloc(instance->buffer.size += 50); if (new_buffer) memcpy(new_buffer, instance->buffer.data, read_len); free(instance->buffer.data); if (!new_buffer) return NULL; instance->buffer.data = new_buffer; buffer = instance->buffer.data + read_len; } } // Terminate the new line with null character and return // Special handling for Windows, terminate at CR if present buffer[read_len >= 2 && buffer[-1] == '\r' ? -1 : 0] = '\0'; } The allium_start function creates the redirection pipes and the child process, the other allium_read_stdout_line function reads from the stdout pipe created by the first function, ReadFile in this function does not return when the child ends or gets killed.

      I appriciate the help of the WinAPI gurus here, thanks in advance!
    • By VADemon
      I've encountered a problem with a single file where I cannot retrieve it's Date-time. So far my code has worked well for over 30 files, but this one is a mystery I cannot debug myself due to insufficient Au3 knowledge.
      In line 11 "_Date_Time_FileTimeToArray" is called and for this particular file it sets the @error to 10. I don't know what that error code means, but it's not set by the _Date functions themselves I think.
      Overall, it could be a problem caused by any of the functions below, how can I properly debug this? / Does anybody know a what's causing this?
      _WinAPI_CreateFile() / _Date_Time_GetFileTime() / _Date_Time_FileTimeToArray()
      Func _SetFileTimes($sFilePath) Local $monthNumber[13] = ["", "January", "February", "March", "April", "May", "Juny", "July", "August", "September", "October", "November", "December"] Local $dayNumber[7] = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] Local $fHandle = _WinAPI_CreateFile($sFilePath, 2, 2) ; read-only ; may NOT return a valid date for some reason! TODO Local $fTagFILETIME = _Date_Time_GetFileTime($fHandle) _WinAPI_CloseHandle($fHandle) ; This will return an empty array if theres no valid date $fModTime = _Date_Time_FileTimeToArray($fTagFILETIME[2]) ; last Modified if @error <> 10 then Local $year = $fModTime[2] Local $month = $fModTime[0] Local $day = $fModTime[1] Local $hour = $fModTime[3] Local $min = $fModTime[4] Local $sec = $fModTime[5] Local $ms = $fModTime[6] Local $weekday = $fModTime[7] Global $prettyTimestamp = StringFormat("%s, %s %d, %04d %02d:%02d:%02d", $dayNumber[$weekday], $monthNumber[$month], $day, $year, $hour, $min, $sec) Global $uploadDate = StringFormat("%04d-%02d-%02d", $year, $month, $day) $fModTime = _Date_Time_FileTimeToArray(_Date_Time_FileTimeToLocalFileTime($fTagFILETIME[2])) ; last Modified Local $year = $fModTime[2] Local $month = $fModTime[0] Local $day = $fModTime[1] Local $hour = $fModTime[3] Local $min = $fModTime[4] Local $sec = $fModTime[5] Local $ms = $fModTime[6] Local $weekday = $fModTime[7] ; GetUnixTime accounts for Local time, hence feed it local time Global $unixTimestamp = _GetUnixTime($year &"/"& $month &"/"& $day &" "& $hour&":"& $min &":"& $sec) else Global $prettyTimestamp = "N/A" Global $uploadDate = "" Global $unixTimestamp = "N/A" endif endfunc  
      _GetUnixTime returned the year 1601 start date, showing that $fModTime is probably equal 0. (But Why?)
      The file reports these dates in Explorer, it's on local NTFS drive:
      Created: ‎‎Wednesday, ‎31. ‎Januar ‎2018, ‏‎18:55:02
      Modified: ‎Wednesday, ‎10. ‎Januar ‎2018, ‏‎12:39:23
      Accessed: ‎Wednesday, ‎10. ‎Januar ‎2018, ‏‎12:39:23
    • By astrionn
      Hi Guys,
      I`m trying to record with my webcam in 5s intervalls and do some stuff between starting to record and stoping.
      I took code from here: https://www.autoitscript.com/forum/topic/27925-webcam-example/
      and took what looked relevant to me.
      I use 3 different files:
       Is called WMS.au3 and contains all the constants for the dll calls is called rec.au3 and does all necessary dll calls to start a webcam recording to a file Is called stopcam.exe and does the dll calls to stop recording into a file WMS.au3  :
      #include <WMS.au3> #include <GUIConstants.au3> if not FileExists(@ScriptDir&"\vid\"&string(@MON)&"\"&string(@mday)) Then DirCreate(@ScriptDir&"\vid\"&"\"&string(@MON)&"\"&string(@mday)) EndIf $moviefile = @ScriptDir&"\vid"&"\"&string(@MON)&"\"&string(@mday)&"\test.avi" $avi = DllOpen("avicap32.dll") $user = DllOpen("user32.dll") FileWrite(@scriptdir&"\clop.clop",$user) $Main = GUICreate("Camera",350,270) $moviefile=@ScriptDir&"\test.avi" $cap = DllCall($avi, "int", "capCreateCaptureWindow", "str", "cap", "int", BitOR($WS_CHILD,$WS_VISIBLE), "int", 15, "int", 15, "int", 320, "int", 240, "hwnd", $Main, "int", 1) FileWrite(@scriptdir&"\clip.clip",$cap[0]) run(@scriptdir&"\stopcam.exe") DllCall($user, "int", "SendMessage", "hWnd", $cap[0], "int", $WM_CAP_DRIVER_CONNECT, "int", 0, "int", 0) DllCall($user, "int", "SendMessage", "hWnd", $cap[0], "int", $WM_CAP_SET_SCALE, "int", 1, "int", 0) DllCall($user, "int", "SendMessage", "hWnd", $cap[0], "int", $WM_CAP_SET_OVERLAY, "int", 1, "int", 0) DllCall($user, "int", "SendMessage", "hWnd", $cap[0], "int", $WM_CAP_SET_PREVIEW, "int", 1, "int", 0) DllCall($user, "int", "SendMessage", "hWnd", $cap[0], "int", $WM_CAP_SET_PREVIEWRATE, "int", 1, "int", 0) DllCall($user, "int", "SendMessage", "hWnd", $cap[0], "int", $WM_CAP_FILE_SET_CAPTURE_FILEA, "int", 0, "str", $moviefile) DllCall($user, "int", "SendMessage", "hWnd", $cap[0], "int", $WM_CAP_SEQUENCE, "int", 0, "int", 0) Stopcam.exe is the compiled version of this:
      #include "WMS.au3" #include <GUIConstants.au3> $cap = Int(FileRead(@scriptdir&"\clip.clip")) $user = int(fileread(@scriptdir&"\clop.clop")) Sleep(10000) DllCall($user, "int", "SendMessage", "hWnd", $cap, "int", $WM_CAP_STOP, "int", 0, "int", 0) DllCall($user, "int", "SendMessage", "hWnd", $cap, "int", $WM_CAP_END, "int", 0, "int", 0) DllCall($user, "int", "SendMessage", "hWnd", $cap, "int", $WM_CAP_DRIVER_DISCONNECT, "int", 0, "int", 0) DllClose($user) FileDelete(@scriptdir&"\clip.clip") FileDelete(@scriptdir&"\clop.clop")  
      Unfortunately this is not working as I thought it would be working.
      Does someone see what I´m doing wrong?
      It should record the webcam for about 10 seconds ( a little less) and save that to an .avi file.
      It does not stop the recording , I have to stop the process manually...
      Secondly, which confuses me more is that it creates the test.avi not in the location is specified in the script... its stored in the ScriptDir for whatever reason haha
      I hope you can help me
    • By badcoder123
      I was looking around the help file and I came across _GDIPlus_GraphicsDrawRect and _WinAPI_DrawLine and I seem to be having the same "problem" where every time it draws into a window and you lose or gain focus it has to redraw itself. Is there anyway around this? 
      #include <WindowsConstants.au3> #include <WinAPI.au3> #Include <GDIPlus.au3> _GDIPlus_Startup() Run("notepad.exe") $hWnd = WinWait("Untitled") $hGraphic = _GDIPlus_GraphicsCreateFromHWND($hWnd) $Color = 0xFFFF0000 $hPen = _GDIPlus_PenCreate($Color, 2) For $i = 1 To 10 _GDIPlus_GraphicsDrawRect($hGraphic, 200, 200, 25 ,25, $hPen) ToolTip($i) Sleep(1000) Next _WinAPI_RedrawWindow($hWnd, 0, 0, $RDW_INVALIDATE + $RDW_ALLCHILDREN) _GDIPlus_GraphicsDispose($hGraphic) _GDIPlus_PenDispose($hPen) _GDIPlus_Shutdown()  
  • Create New...