Results 1 to 28 of 28

Thread: Help: Pointers Problems

  1. #1

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Help: Pointers Problems

    Ok well basically I have attempting to format a file path based on some path input. And I found I can do this with a Native API Function. Problem is, it seems all Native API use pointers, and I really really really hate pointers.

    Example:
    User Input: c:\windows\system32\cmd.exe
    Output: C:\WINDOWS\system32\cmd.exe

    I feel like giving up, but I think I am close.

    Here is my code: [EDIT In next post b/c of word limit]





    Iv been trying all different ways to use the CopyMemory function combined with PtrVar and StrPrt and all that stuff. But I can not just figure this out.


    So 2 Questions:
    1. Is there an easier way?
    2. How can I use these damn pointers, because I know I am going to come across them soon again since I am trying to discover many of the Hidden Native API functions.


    Please help if you can.

  2. #2

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    CODE:
    Code:
    'Does not return file path:
    'Private Declare Function GetFullPathName Lib "kernel32.dll" Alias "GetFullPathNameA" (ByVal lpFileName As String, ByVal nBufferLength As Long, ByVal lpBuffer As String, ByVal lpFilePart As String) As Long
    
    
    '--------------------------------
    
    'Does not return file path:
    'Private Declare Function GetFileInformationByHandle Lib "kernel32" (ByVal hFile As Integer, ByRef lpFileInformation As BY_HANDLE_FILE_INFORMATION) As Integer
    
    'Only works in vista:
    'Private Declare Function GetFileInformationByHandleEx Lib "kernel32" (ByVal hFile As Integer, ByVal FileInformationClass As Long, ByRef lpFileInformation As Any, ByVal dwBufferSize As Long) As Integer
    
    
    'Private Enum FILE_INFO_BY_HANDLE_CLASS
    '    FileBasicInfo
    '    FileStandardInfo
    '    FileNameInfo
    '    FileRenameInfo
    '    FileDispositionInfo
    '    FileAllocationInfo
    '    FileEndOfFileInfo
    '    FileStreamInfo
    '    FileCompressionInfo
    '    FileAttributeTagInfo
    '    FileIdBothDirectoryInfo
    '    FileIdBothDirectoryRestartInfo
    '    FileIoPriorityHintInfo
    '    MaximumFileInfoByHandlesClass
    'End Enum
    '
    'Private Type FILE_NAME_INFO
    '    FileNameLength As Long
    '    FileName As String
    'End Type
    
    '--------------------------------------------------------------------------------------------------------------------------
    
    'typedef enum _FILE_INFORMATION_CLASS {
    '    FileDirectoryInformation = 1, // 1 Y N D
    '    FileFullDirectoryInformation, // 2 Y N D
    '    FileBothDirectoryInformation, // 3 Y N D
    '    FileBasicInformation, // 4 Y Y F
    '    FileStandardInformation, // 5 Y N F
    '    FileInternalInformation, // 6 Y N F
    '    FileEaInformation, // 7 Y N F
    '    FileAccessInformation, // 8 Y N F
    '    FileNameInformation, // 9 Y N F
    '    FileRenameInformation, // 10 N Y F
    '    FileLinkInformation, // 11 N Y F
    '    FileNamesInformation, // 12 Y N D
    '    FileDispositionInformation, // 13 N Y F
    '    FilePositionInformation, // 14 Y Y F
    '    FileModeInformation = 16, // 16 Y Y F
    '    FileAlignmentInformation, // 17 Y N F
    '    FileAllInformation, // 18 Y N F
    '    FileAllocationInformation, // 19 N Y F
    '    FileEndOfFileInformation, // 20 N Y F
    '    FileAlternateNameInformation, // 21 Y N F
    '    FileStreamInformation, // 22 Y N F
    '    FilePipeInformation, // 23 Y Y F
    '    FilePipeLocalInformation, // 24 Y N F
    '    FilePipeRemoteInformation, // 25 Y Y F
    '    FileMailslotQueryInformation, // 26 Y N F
    '    FileMailslotSetInformation, // 27 N Y F
    '    FileCompressionInformation, // 28 Y N F
    '    FileObjectIdInformation, // 29 Y Y F
    '    FileCompletionInformation, // 30 N Y F
    '    FileMoveClusterInformation, // 31 N Y F
    '    FileQuotaInformation, // 32 Y Y F
    '    FileReparsePointInformation, // 33 Y N F
    '    FileNetworkOpenInformation, // 34 Y N F
    '    FileAttributeTagInformation, // 35 Y N F
    '    FileTrackingInformation // 36 N Y F
    '} FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS;
    
    
    
    Private Type IO_STATUS_BLOCK
         Status As Long
         Information As Long
    End Type
    
    'Used for IO_FILE_IO_PRIORITY_HINT_INFORMATION in FileInformationClass
    Private Type IO_PRIORITY_HINT
        IoPriorityVeryLow As Long
        IoPriorityLow As Long
        IoPriorityNormal As Long
        IoPriorityHigh As Long
        IoPriorityCritical As Long
        MaxIoPriorityTypes As Long
    End Type
    
    
    'FileInformationClass:
    '-----------------------------------------------
    Private Type FILE_ALIGNMENT_INFORMATION
        AlignmentRequirement As Long
    End Type
    
    Private Type FILE_ATTRIBUTE_TAG_INFORMATION
        FileAttributes As Long
        ReparseTag As Long
    End Type
    
    Private Type FILE_BASIC_INFORMATION
        CreationTime As Long
        LastAccessTime As Long
        LastWriteTime As Long
        ChangeTime As Long
        FileAttribute As Long
    End Type
    
    Private Type FILE_IO_PRIORITY_HINT_INFORMATION
        PriorityHint As Long
    End Type
    
    Private Type FILE_NAME_INFORMATION
        FileNameLength As Long
        FileName As String * 255
    End Type
    
    Private Type FILE_NETWORK_OPEN_INFORMATION
        CreationTime As Long
        LastAccessTime As Long
        LastWriteTime As Long
        ChangeTime As Long
        FileAttribute As Long
        AllocationSize As Long
        EndOfFile As Long
        FileAttributes As Long
    End Type
    
    Private Type FILE_POSITION_INFORMATION
        CurrentByteOffset As Long
    End Type
    
    Private Type FILE_STANDARD_INFORMATION
        AllocationSize As Long
        EndOfFile As Long
        NumberOfLinks As Long
        DeletePending As Boolean
        Directory As Boolean
    End Type
    
    
    '[------------------]
    '[------------------]
    
    Private Enum FileInformationClass
        FileAlignmentInformation
        FileAttributeTagInformation
        FileBasicInformation
        FileIoPriorityHintInformation
        FileNameInformation
        FileNetworkOpenInformation
        FilePositionInformation
        FileStandardInformation
    End Enum
    '-----------------------------------------------
    
    
    
    '  ZwQueryInformationFile(
    '    IN HANDLE  FileHandle,
    '    OUT PIO_STATUS_BLOCK  IoStatusBlock,
    '    OUT PVOID  FileInformation,
    '    IN ULONG  Length,
    '    IN FILE_INFORMATION_CLASS  FileInformationClass
    '    );
    
    Private Declare Function ZwQueryInformationFile Lib "ntdll.dll" (ByVal FileHandle As Long, ByRef IoStatusBlock As IO_STATUS_BLOCK, ByRef FileInformation As Any, ByVal Length As Long, ByVal FileInformationClass As Long) As Long
    
    Private Declare Function NtQueryInformationFile Lib "ntdll.dll" (ByVal FileHandle As Long, IoStatusBlock As IO_STATUS_BLOCK, ByRef FileInformation As Any, ByVal Length As Long, ByVal FileInformationClass As Long) As Long
    
    
    
    'Object Attributes:
    '-----------------------------------------------
     Private Type ACL
        AclRevision As Byte
        Sbz1 As Byte
        AclSize As Integer
        AceCount As Integer
        Sbz2 As Integer
    End Type
    
    Private Type SECURITY_DESCRIPTOR
        Revision As Byte
        Sbz1 As Byte
        Control As Long
        Owner As Long
        Group As Long
        Sacl As ACL
        Dacl As ACL
    End Type
    
    Private Type UNICODE_STRING
           Length           As Long
           MaximumLength    As Long
           Buffer           As Long
    End Type
    
    'Private Type OBJECT_ATTRIBUTES
    '    Length                      As Long
    '    RootDirectory               As Long
    '    ObjectName                  As UNICODE_STRING
    '    Attributes                  As Long
    '    SecurityDescriptor          As SECURITY_DESCRIPTOR
    '    SecurityQualityOfService    As Long
    'End Type
    
    Private Type OBJECT_ATTRIBUTES
        Length                      As Long
        RootDirectory               As Long
        ObjectName                  As Long
        Attributes                  As Long
        SecurityDescriptor          As Long
        SecurityQualityOfService    As Long
    End Type
    
    Private Const OBJ_CASE_INSENSITIVE = 64
    Private Const OBJ_INHERIT = 2
    
    '-----------------------------------------------
    
    
    Private Declare Function RtlAnsiStringToUnicodeString Lib "ntdll.dll" (DestinationString As UNICODE_STRING, ByVal SourceString As String, ByVal AllocateDestinationString As Boolean) As Long
    
    
    '  ZwOpenFile(
    '    OUT PHANDLE  FileHandle,
    '    IN ACCESS_MASK  DesiredAccess,
    '    IN POBJECT_ATTRIBUTES  ObjectAttributes,
    '    OUT PIO_STATUS_BLOCK  IoStatusBlock,
    '    IN ULONG  ShareAccess,
    '    IN ULONG  OpenOptions
    '    );
    
    'Open File:
    Private Declare Function ZwOpenFile Lib "ntdll.dll" (ByRef FileHandle As Long, ByVal DesiredAccess As Long, ByRef ObjectAttributes As OBJECT_ATTRIBUTES, ByRef IoStatusBlock As IO_STATUS_BLOCK, ByVal ShareAccess As Long, ByVal OpenOptions As Long) As Long
    
    Private Declare Function NtOpenFile Lib "ntdll.dll" (ByRef FileHandle As Long, ByVal DesiredAccess As Long, ByRef ObjectAttributes As OBJECT_ATTRIBUTES, ByRef IoStatusBlock As IO_STATUS_BLOCK, ByVal ShareAccess As Long, ByVal OpenOptions As Long) As Long
    
        'DesiredAccess:
        Private Const GENERIC_ALL = 28
        Private Const FILE_ALL_ACCESS = 511
        
        Private Const SYNCHRONIZE As Long = &H100000
        Private Const GENERIC_READ As Long = &H80000000
        
        'ShareAccess:
        Private Const FILE_SHARE_READ = &H1
        Private Const FILE_SHARE_WRITE = &H2
        
        'OpenOptions:
        Private Const FILE_NON_DIRECTORY_FILE = 64
        Private Const FILE_DIRECTORY_FILE = 1
        Private Const FILE_SYNCHRONOUS_IO_NONALERT = 32
        
        
    Private Declare Function OpenFile Lib "kernel32" (ByVal lpFileName As String, lpReOpenBuff As OFSTRUCT, ByVal wStyle As Long) As Long
        
        Private Const OFS_MAXPATHNAME = 128
        Private Const OF_READWRITE = &H2
        
        Private Type OFSTRUCT
           cBytes      As Byte
           fFixedDisk  As Byte
           nErrCode    As Integer
           Reserved1   As Integer
           Reserved2   As Integer
           szPathName(0 To OFS_MAXPATHNAME - 1) As Byte '0-based
        End Type
    
    
    
    'Copy Memory:
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
    
    Private Declare Sub CopyMemoryPut Lib "kernel32" Alias "RtlMoveMemory" (ByVal Destination As Long, Source As Any, ByVal Length As Long)
    Private Declare Sub CopyMemoryRead Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, ByVal Source As Long, ByVal Length As Long)

  3. #3

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    Code:
    Private Sub Command1_Click()
        'Text2.Text = FormatFilePath(Text1.Text)
        Text2.Text = FormatFilePath2(Text1.Text)
    End Sub
    
    
    
    Public Function FormatFilePath2(ByVal sPath As String) As String
    
        Dim OFS As OFSTRUCT
        Dim hFile As Long
        
        Dim tUString As UNICODE_STRING
        Dim tIOS As IO_STATUS_BLOCK
        Dim tObjAttr As OBJECT_ATTRIBUTES
        Dim tFileName As FILE_NAME_INFORMATION
        
        Dim lSize As Long
        
        Dim lReturn0 As Long
        Dim lReturn As Long
        
        'Convert unicode string:
        'lReturn = RtlAnsiStringToUnicodeString(tUString, sPath, True)
        
            'MsgBox lReturn
        
        'Initialize attributes:
        tUString.Length = Len(sPath) * 2
        tUString.Buffer = StrPtr(sPath)
        
        
        tObjAttr.Length = Len(tObjAttr)
        tObjAttr.ObjectName = VarPtr(tUString)
        tObjAttr.Attributes = OBJ_CASE_INSENSITIVE Or OBJ_INHERIT
        
        
        'Open File:
        hFile = OpenFile(sPath, OFS, OF_READWRITE)
        'lReturn0 = ZwOpenFile(hFile, FILE_ALL_ACCESS, 0, tIOS, FILE_SHARE_READ Or FILE_SHARE_WRITE, FILE_NON_DIRECTORY_FILE)
        'lReturn0 = NtOpenFile(hFile, GENERIC_READ Or SYNCHRONIZE, tObjAttr, tIOS, FILE_SHARE_READ, FILE_NON_DIRECTORY_FILE Or FILE_SYNCHRONOUS_IO_NONALERT)
        
            'MsgBox GetSysMsg(lReturn0)
            MsgBox "hFile  = " & hFile
        
    
        'Set buffer & size:
        'tFileName.FileName = String(260, Chr(0))
        lSize = LenB(tFileName)
        
            MsgBox lSize
        
        
        'Fill data structure:
        'lReturn = ZwQueryInformationFile(hFile, tIOS, tFileName, lSize, 9)
        lReturn = NtQueryInformationFile(hFile, VarPtr(tIOS), VarPtr(tFileName), lSize, 9)
        
        Dim sValue As String
        Call CopyMemoryRead(StrPtr(sValue), VarPtr(tFileName), (Len(tFileName)))
        
            'Call (CopyMemory sValue,len(tFileName))
            MsgBox sValue
            MsgBox Len(sValue)
        
            'CopyMemoryRead le, ptr, 504
            'struct.strData = le.strData
            'struct.pNext = le.pNext
        
        
            MsgBox GetSysMsg(lReturn)
            MsgBox LenB(tFileName)
            MsgBox tFileName.FileName
        
        'display file name:
        FormatFilePath2 = tFileName.FileName
    
    End Function
    
    
    
    
    'Public Function FormatFilePath(ByVal sPath As String) As String
    '
    '    Dim OFS As OFSTRUCT
    '    Dim hFile As Long
    '
    '    Dim tFileName As FILE_NAME_INFO
    '    Dim lSize As Long
    '
    '
    '    'Open File:
    '    hFile = OpenFile(sPath, OFS, OF_READWRITE)
    '
    '    'Set buffer size:
    '    lSize = Len(FILE_NAME_INFO)
    '
    '    'Fill data structure:
    '    Call GetFileInformationByHandleEx(hFile, FILE_INFO_BY_HANDLE_CLASS.FileNameInfo, tFileName, lSize)
    '
    '    'display file name:
    '    FormatFilePath = tFileName.FileName
    '
    'End Function

  4. #4

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    Ok, well I have been getting farther and farther on this as time is continuing onward. But now, I am stuck at a block of code that is very important but this copy memory function is not liking me right now haha.

    Ok so take a look at my last post here:
    http://www.codeguru.com/forum/showthread.php?t=421763

    Dealing the the hunt for the solution for the following block of code:
    Code:
        'Move pointer to variable:
        Dim tFNI As FNI
        'Call CopyMemory(tFNI, ByVal ptr, Len(ptr))
        'Call CopyMemory(ByVal VarPtr(tFNI), ByVal ptr, lSize)
        'Call CopyMemory(VarPtr(tFNI), ByVal ptr, Len(ptr))
        Call CopyMemoryRead(ByVal VarPtr(tFNI), ByVal VarPtr(ptr), Len(ptr))

    Feel free to post in that topic or this one for any help that you have. thanks a lot for any attempts.

  5. #5
    Junior Member
    Join Date
    Feb 2007
    Posts
    27

    Re: Help: Pointers Problems

    Would you mind explaining in details what exactly are you trying to do?

    Because, I don't see any real difference between the paths you mentioned, besides the casing, which seems rather irrelevant. Moreover, it seems to me you're trying methods way too complicated if all you're trying to do is make sure the path has the correct case as the files in disk :\

  6. #6
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: Help: Pointers Problems

    I think you're making life way too hard for yourself.

    You do not need to convert VB strings to Unicode. (And anyway, VB provides a function, StrConv, that does that for you.) VB strings are stored internally as Unicode.
    And, if you want to call an ANSI function, you should not do anything. Just declare the parameters as Strings and VB converts them to ANSI automatically.
    If you want to call a Unicode function, declare the string parameters, and use StrPtr to pass a pointer to the string buffer.

    Pointers are not hard to understand. You need to get your head around the concepts of referencing and dereferencing in order to do any serious programming.


    Having said all that: to do what you want, I am pretty sure you can just use built-in VB functions:
    Code:
    ChDir "c:\windows\SyStEm32"
    MsgBox CurDir & "\cmd.exe"
    Last edited by penagate; Apr 29th, 2007 at 02:49 AM.

  7. #7

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    Well here is the thing, I alread solved the problem by making a sricpt file which I can input into a function in VB.

    Right now I want to figure out the Native API way since this will help me learn how to better understand them so I can start using them more often for problems that cant just be solved by some script.

    That is why I need help in that pointer resolution problem.
    Last edited by altf4; Apr 29th, 2007 at 09:20 AM.

  8. #8
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: Help: Pointers Problems

    Pick an API function that you don't understand how to use, and I'll do my best to explain it to you (unless I don't understand it myself ).

  9. #9

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    CopyMemory is one of them. I dont understand how to know when to pass thing byval and byref and why you have to use VarPtr when trying to get the Ptr to the Var with the copy memory anyways.
    I mean the msdn data base shows copymemory with all specifications as [in], so why would byref work instead of byval. it doesn't make sence.

    Also, is the length param the size of the source or destination?

    So please explain that if you can.

    Also do you have any idea why the block of code I posted above crashes no matter what variation i try? Its something with the copymemory function not properly working.


    So here is an example:
    Code:
    Private Type Data
        Value1 As Long
        Value2 As String * 255
        Value3 As Integer
    End Type
    
    
    Private Declare Function PerformAction Lib "dll.dll" (ByRef pStructure As Any) As Long
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
    
    
    Private Sub Command1_Click()
    
        '--------------
        'Variables:
    
        Dim tData As Data   'data structure
        Dim pData As Long   'structure pointer
        
        Dim lVarSize As Long
        Dim lPtrSize As Long
        
    
        '--------------
        'Code:
        
        'Get pointer:
        pData = VarPtr(tData)
        
        'Store Sizes:
        lVarSize = Len(tData)
        lPtrSize = Len(pData)
        
        'Fill data structure using pointer value:
        Call PerformAction(pData)
        
        
        'Retrive data structure from pointer: (Area that needs Explianation)
        
            '1. Var = ByVal, Ptr = ByRef
                Call CopyMemory(ByVal tData, pData, lVarSize)
                Call CopyMemory(ByVal tData, pData, lPtrSize)
                    
                    'VarPtr = Dest
                        Call CopyMemory(ByVal VarPtr(tData), pData, lVarSize)
                        Call CopyMemory(ByVal VarPtr(tData), pData, lPtrSize)
                        
                    'VarPtr = Src
                        Call CopyMemory(ByVal tData, VarPtr(pData), lVarSize)
                        Call CopyMemory(ByVal tData, VarPtr(pData), lPtrSize)
                        
                    'VarPtr = Both
                        Call CopyMemory(ByVal VarPtr(tData), VarPtr(pData), lVarSize)
                        Call CopyMemory(ByVal VarPtr(tData), VarPtr(pData), lPtrSize)
                
                
                
            
            '2. Var = ByRef, Ptr = ByVal
                Call CopyMemory(tData, ByVal pData, lVarSize)
                Call CopyMemory(tData, ByVal pData, lPtrSize)
                    
                    'VarPtr = Dest
                        Call CopyMemory(VarPtr(tData), ByVal pData, lVarSize)
                        Call CopyMemory(VarPtr(tData), ByVal pData, lPtrSize)
                        
                    'VarPtr = Src
                        Call CopyMemory(tData, ByVal VarPtr(pData), lVarSize)
                        Call CopyMemory(tData, ByVal VarPtr(pData), lPtrSize)
                        
                    'VarPtr = Both
                        Call CopyMemory(VarPtr(tData), ByVal VarPtr(pData), lVarSize)
                        Call CopyMemory(VarPtr(tData), ByVal VarPtr(pData), lPtrSize)
                   
                   
                   
                   
            '3. Var = ByRef, Ptr = ByRef
                Call CopyMemory(tData, pData, lVarSize)
                Call CopyMemory(tData, pData, lPtrSize)
                    
                    'VarPtr = Dest
                        Call CopyMemory(VarPtr(tData), pData, lVarSize)
                        Call CopyMemory(VarPtr(tData), pData, lPtrSize)
                        
                    'VarPtr = Src
                        Call CopyMemory(tData, VarPtr(pData), lVarSize)
                        Call CopyMemory(tData, VarPtr(pData), lPtrSize)
                        
                    'VarPtr = Both
                        Call CopyMemory(VarPtr(tData), VarPtr(pData), lVarSize)
                        Call CopyMemory(VarPtr(tData), VarPtr(pData), lPtrSize)
                        
                        
                        
            '4. Var = ByVal, Ptr = ByVal
                Call CopyMemory(ByVal tData, ByVal pData, lVarSize)
                Call CopyMemory(ByVal tData, ByVal pData, lPtrSize)
                    
                    'VarPtr = Dest
                        Call CopyMemory(ByVal VarPtr(tData), ByVal pData, lVarSize)
                        Call CopyMemory(ByVal VarPtr(tData), ByVal pData, lPtrSize)
                        
                    'VarPtr = Src
                        Call CopyMemory(ByVal tData, ByVal VarPtr(pData), lVarSize)
                        Call CopyMemory(ByVal tData, ByVal VarPtr(pData), lPtrSize)
                        
                    'VarPtr = Both
                        Call CopyMemory(ByVal VarPtr(tData), ByVal VarPtr(pData), lVarSize)
                        Call CopyMemory(ByVal VarPtr(tData), ByVal VarPtr(pData), lPtrSize)
        
        
    
    End Sub
    Basically, 1 of those 32 different combos I know work. But the probelm is, how do you tell which one it is?


    This is basically what kills my mind with how do you know which one to use in which case?
    Last edited by altf4; Apr 29th, 2007 at 12:41 PM.

  10. #10
    Junior Member
    Join Date
    Feb 2007
    Posts
    27

    Re: Help: Pointers Problems

    Quote Originally Posted by altf4
    CopyMemory is one of them. I dont understand how to know when to pass thing byval and byref and why you have to use VarPtr when trying to get the Ptr to the Var with the copy memory anyways.
    I mean the msdn data base shows copymemory with all specifications as [in], so why would byref work instead of byval. it doesn't make sence.
    Pointers always have to be passed ByVal, while if you pass a variable directly (and let VB handle it's pointer internally), you may choose whether to allow the function to change the data or not.

    So basically, if you're passing a String for instance, pass it ByRef, while if you're passing a pointer, pass it ByVal.

    Quote Originally Posted by altf4
    Also, is the length param the size of the source or destination?
    Its the amount of bytes to copy from the Source into the specified Destination.

    Quote Originally Posted by altf4
    Also do you have any idea why the block of code I posted above crashes no matter what variation i try? Its something with the copymemory function not properly working.


    So here is an example:
    Code:
    Private Type Data
        Value1 As Long
        Value2 As String * 255
        Value3 As Integer
    End Type
    
    
    Private Declare Function PerformAction Lib "dll.dll" (ByRef pStructure As Any) As Long
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
    
    
    Private Sub Command1_Click()
    
        '--------------
        'Variables:
    
        Dim tData As Data   'data structure
        Dim pData As Long   'structure pointer
        
        Dim lVarSize As Long
        Dim lPtrSize As Long
        
    
        '--------------
        'Code:
        
        'Get pointer:
        pData = VarPtr(tData)
        
        'Store Sizes:
        lVarSize = Len(tData)
        lPtrSize = Len(pData)
        
        'Fill data structure using pointer value:
        Call PerformAction(pData)
        
        
        'Retrive data structure from pointer: (Area that needs Explianation)
        
            '1. Var = ByVal, Ptr = ByRef
                Call CopyMemory(ByVal tData, pData, lVarSize)
                Call CopyMemory(ByVal tData, pData, lPtrSize)
                    
                    'VarPtr = Dest
                        Call CopyMemory(ByVal VarPtr(tData), pData, lVarSize)
                        Call CopyMemory(ByVal VarPtr(tData), pData, lPtrSize)
                        
                    'VarPtr = Src
                        Call CopyMemory(ByVal tData, VarPtr(pData), lVarSize)
                        Call CopyMemory(ByVal tData, VarPtr(pData), lPtrSize)
                        
                    'VarPtr = Both
                        Call CopyMemory(ByVal VarPtr(tData), VarPtr(pData), lVarSize)
                        Call CopyMemory(ByVal VarPtr(tData), VarPtr(pData), lPtrSize)
                
                
                
            
            '2. Var = ByRef, Ptr = ByVal
                Call CopyMemory(tData, ByVal pData, lVarSize)
                Call CopyMemory(tData, ByVal pData, lPtrSize)
                    
                    'VarPtr = Dest
                        Call CopyMemory(VarPtr(tData), ByVal pData, lVarSize)
                        Call CopyMemory(VarPtr(tData), ByVal pData, lPtrSize)
                        
                    'VarPtr = Src
                        Call CopyMemory(tData, ByVal VarPtr(pData), lVarSize)
                        Call CopyMemory(tData, ByVal VarPtr(pData), lPtrSize)
                        
                    'VarPtr = Both
                        Call CopyMemory(VarPtr(tData), ByVal VarPtr(pData), lVarSize)
                        Call CopyMemory(VarPtr(tData), ByVal VarPtr(pData), lPtrSize)
                   
                   
                   
                   
            '3. Var = ByRef, Ptr = ByRef
                Call CopyMemory(tData, pData, lVarSize)
                Call CopyMemory(tData, pData, lPtrSize)
                    
                    'VarPtr = Dest
                        Call CopyMemory(VarPtr(tData), pData, lVarSize)
                        Call CopyMemory(VarPtr(tData), pData, lPtrSize)
                        
                    'VarPtr = Src
                        Call CopyMemory(tData, VarPtr(pData), lVarSize)
                        Call CopyMemory(tData, VarPtr(pData), lPtrSize)
                        
                    'VarPtr = Both
                        Call CopyMemory(VarPtr(tData), VarPtr(pData), lVarSize)
                        Call CopyMemory(VarPtr(tData), VarPtr(pData), lPtrSize)
                        
                        
                        
            '4. Var = ByVal, Ptr = ByVal
                Call CopyMemory(ByVal tData, ByVal pData, lVarSize)
                Call CopyMemory(ByVal tData, ByVal pData, lPtrSize)
                    
                    'VarPtr = Dest
                        Call CopyMemory(ByVal VarPtr(tData), ByVal pData, lVarSize)
                        Call CopyMemory(ByVal VarPtr(tData), ByVal pData, lPtrSize)
                        
                    'VarPtr = Src
                        Call CopyMemory(ByVal tData, ByVal VarPtr(pData), lVarSize)
                        Call CopyMemory(ByVal tData, ByVal VarPtr(pData), lPtrSize)
                        
                    'VarPtr = Both
                        Call CopyMemory(ByVal VarPtr(tData), ByVal VarPtr(pData), lVarSize)
                        Call CopyMemory(ByVal VarPtr(tData), ByVal VarPtr(pData), lPtrSize)
        
        
    
    End Sub
    Basically, 1 of those 32 different combos I know work. But the probelm is, how do you tell which one it is?

    This is basically what kills my mind with how do you know which one to use in which case?
    The following code does work. Since i didn't have the PerformAction function in that DLL, i made a random one to fill the structure.
    Code:
    Private Function PerformAction(ByRef pStructure As Long) As Long
    
    Dim Result As Data
    
    Result.Value1 = 1337
    Result.Value2 = "Insert Random String Here"
    Result.Value3 = 7887
    
    Call CopyMemory(ByVal pStructure, ByVal VarPtr(Result), LenB(Result))
    
    End Function
    
    Private Sub Command1_Click()
    
    Dim tData As Data   'data structure
    Dim pData As Long   'structure pointer
    
    'Get pointer:
    
    pData = VarPtr(tData)
    
    'Fill data structure using pointer value:
    
    Call PerformAction(pData)
    
    Debug.Print tData.Value1
    Debug.Print tData.Value2
    Debug.Print tData.Value3
    
    Dim tNewData As Data
    
    Call CopyMemory(ByVal VarPtr(tNewData), ByVal pData, LenB(tNewData))
    
    Debug.Print tNewData.Value1
    Debug.Print tNewData.Value2
    Debug.Print tNewData.Value3
    
    End Sub
    Last edited by -=NightWolf=-; Apr 29th, 2007 at 01:31 PM.

  11. #11

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    Ok thanks for the explaination, but I tried what you said and it still crashed.

    Here is this code:

    General Declarations (Part 1):
    Code:
    Option Explicit
    
    'Does not return file path:
    'Private Declare Function GetFullPathName Lib "kernel32.dll" Alias "GetFullPathNameA" (ByVal lpFileName As String, ByVal nBufferLength As Long, ByVal lpBuffer As String, ByVal lpFilePart As String) As Long
    
    '--------------------------------
    
    'Does not return file path:
    'Private Declare Function GetFileInformationByHandle Lib "kernel32" (ByVal hFile As Integer, ByRef lpFileInformation As BY_HANDLE_FILE_INFORMATION) As Integer
    
    'Only works in vista:
    'Private Declare Function GetFileInformationByHandleEx Lib "kernel32" (ByVal hFile As Integer, ByVal FileInformationClass As Long, ByRef lpFileInformation As Any, ByVal dwBufferSize As Long) As Integer
    
    
    'Private Enum FILE_INFO_BY_HANDLE_CLASS
    '    FileBasicInfo
    '    FileStandardInfo
    '    FileNameInfo
    '    FileRenameInfo
    '    FileDispositionInfo
    '    FileAllocationInfo
    '    FileEndOfFileInfo
    '    FileStreamInfo
    '    FileCompressionInfo
    '    FileAttributeTagInfo
    '    FileIdBothDirectoryInfo
    '    FileIdBothDirectoryRestartInfo
    '    FileIoPriorityHintInfo
    '    MaximumFileInfoByHandlesClass
    'End Enum
    '
    'Private Type FILE_NAME_INFO
    '    FileNameLength As Long
    '    FileName As String
    'End Type
    
    '--------------------------------------------------------------------------------------------------------------------------
    
    'typedef enum _FILE_INFORMATION_CLASS {
    '    FileDirectoryInformation = 1, // 1 Y N D
    '    FileFullDirectoryInformation, // 2 Y N D
    '    FileBothDirectoryInformation, // 3 Y N D
    '    FileBasicInformation, // 4 Y Y F
    '    FileStandardInformation, // 5 Y N F
    '    FileInternalInformation, // 6 Y N F
    '    FileEaInformation, // 7 Y N F
    '    FileAccessInformation, // 8 Y N F
    '    FileNameInformation, // 9 Y N F
    '    FileRenameInformation, // 10 N Y F
    '    FileLinkInformation, // 11 N Y F
    '    FileNamesInformation, // 12 Y N D
    '    FileDispositionInformation, // 13 N Y F
    '    FilePositionInformation, // 14 Y Y F
    '    FileModeInformation = 16, // 16 Y Y F
    '    FileAlignmentInformation, // 17 Y N F
    '    FileAllInformation, // 18 Y N F
    '    FileAllocationInformation, // 19 N Y F
    '    FileEndOfFileInformation, // 20 N Y F
    '    FileAlternateNameInformation, // 21 Y N F
    '    FileStreamInformation, // 22 Y N F
    '    FilePipeInformation, // 23 Y Y F
    '    FilePipeLocalInformation, // 24 Y N F
    '    FilePipeRemoteInformation, // 25 Y Y F
    '    FileMailslotQueryInformation, // 26 Y N F
    '    FileMailslotSetInformation, // 27 N Y F
    '    FileCompressionInformation, // 28 Y N F
    '    FileObjectIdInformation, // 29 Y Y F
    '    FileCompletionInformation, // 30 N Y F
    '    FileMoveClusterInformation, // 31 N Y F
    '    FileQuotaInformation, // 32 Y Y F
    '    FileReparsePointInformation, // 33 Y N F
    '    FileNetworkOpenInformation, // 34 Y N F
    '    FileAttributeTagInformation, // 35 Y N F
    '    FileTrackingInformation // 36 N Y F
    '} FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS;
    
    
    Private Type IO_STATUS_BLOCK
         Status As Long
         Information As Long
    End Type
    
    'Used for IO_FILE_IO_PRIORITY_HINT_INFORMATION in FileInformationClass
    Private Type IO_PRIORITY_HINT
        IoPriorityVeryLow As Long
        IoPriorityLow As Long
        IoPriorityNormal As Long
        IoPriorityHigh As Long
        IoPriorityCritical As Long
        MaxIoPriorityTypes As Long
    End Type
    
    Private Type UNICODE_STRING
           Length           As Long
           MaximumLength    As Long
           Buffer           As Long
    End Type
    
    
    'FileInformationClass:
    '-----------------------------------------------
    Private Type FILE_ALIGNMENT_INFORMATION
        AlignmentRequirement As Long
    End Type
    
    Private Type FILE_ATTRIBUTE_TAG_INFORMATION
        FileAttributes As Long
        ReparseTag As Long
    End Type
    
    Private Type FILE_BASIC_INFORMATION
        CreationTime As Long
        LastAccessTime As Long
        LastWriteTime As Long
        ChangeTime As Long
        FileAttribute As Long
    End Type
    
    Private Type FILE_IO_PRIORITY_HINT_INFORMATION
        PriorityHint As Long
    End Type
    
    Private Type FILE_NAME_INFORMATION
        FileNameLength As Long
        FileName As UNICODE_STRING
    End Type
    
    Private Type FNI
        FileNameLength As Long
        FileName As UNICODE_STRING
    End Type
    
    
    Private Type FILE_NETWORK_OPEN_INFORMATION
        CreationTime As Long
        LastAccessTime As Long
        LastWriteTime As Long
        ChangeTime As Long
        FileAttribute As Long
        AllocationSize As Long
        EndOfFile As Long
        FileAttributes As Long
    End Type
    
    Private Type FILE_POSITION_INFORMATION
        CurrentByteOffset As Long
    End Type
    
    Private Type FILE_STANDARD_INFORMATION
        AllocationSize As Long
        EndOfFile As Long
        NumberOfLinks As Long
        DeletePending As Boolean
        Directory As Boolean
    End Type
    
    '[------------------]
    '[------------------]
    
    'Private Enum FileInformationClass
    '    FileAlignmentInformation
    '    FileAttributeTagInformation
    '    FileBasicInformation
    '    FileIoPriorityHintInformation
    '    FileNameInformation
    '    FileNetworkOpenInformation
    '    FilePositionInformation
    '    FileStandardInformation
    'End Enum
    '-----------------------------------------------
    
    
    '  ZwQueryInformationFile(
    '    IN HANDLE  FileHandle,
    '    OUT PIO_STATUS_BLOCK  IoStatusBlock,
    '    OUT PVOID  FileInformation,
    '    IN ULONG  Length,
    '    IN FILE_INFORMATION_CLASS  FileInformationClass
    '    );
    
    Private Declare Function ZwQueryInformationFile Lib "ntdll.dll" (ByVal FileHandle As Long, ByRef IoStatusBlock As IO_STATUS_BLOCK, ByRef FileInformation As Any, ByVal Length As Long, ByVal FileInformationClass As Long) As Long
    
    Private Declare Function NtQueryInformationFile Lib "ntdll.dll" (ByVal FileHandle As Long, IoStatusBlock As IO_STATUS_BLOCK, ByRef FileInformation As Any, ByVal Length As Long, ByVal FileInformationClass As Long) As Long
    
    'Private Declare Function NtQueryInformationFile Lib "NTDLL.DLL" ( _
    'ByVal FileHandle As Long, _
    'IoStatusBlock_Out As IO_STATUS_BLOCK, _
    'lpFileInformation_Out As Long, _
    'ByVal Length As Long, _
    'ByVal FileInformationClass As Long) As Long
    
    
    'Object Attributes:
    '-----------------------------------------------
     Private Type ACL
        AclRevision As Byte
        Sbz1 As Byte
        AclSize As Integer
        AceCount As Integer
        Sbz2 As Integer
    End Type
    
    Private Type SECURITY_DESCRIPTOR
        Revision As Byte
        Sbz1 As Byte
        Control As Long
        Owner As Long
        Group As Long
        Sacl As ACL
        Dacl As ACL
    End Type
    
    'Private Type OBJECT_ATTRIBUTES
    '    Length                      As Long
    '    RootDirectory               As Long
    '    ObjectName                  As UNICODE_STRING
    '    Attributes                  As Long
    '    SecurityDescriptor          As SECURITY_DESCRIPTOR
    '    SecurityQualityOfService    As Long
    'End Type
    
    Private Type OBJECT_ATTRIBUTES
        Length                      As Long
        RootDirectory               As Long
        ObjectName                  As Long
        Attributes                  As Long
        SecurityDescriptor          As Long
        SecurityQualityOfService    As Long
    End Type
    
    Private Const OBJ_CASE_INSENSITIVE = 64
    Private Const OBJ_INHERIT = 2
    
    '-----------------------------------------------
    
    
    '  ZwOpenFile(
    '    OUT PHANDLE  FileHandle,
    '    IN ACCESS_MASK  DesiredAccess,
    '    IN POBJECT_ATTRIBUTES  ObjectAttributes,
    '    OUT PIO_STATUS_BLOCK  IoStatusBlock,
    '    IN ULONG  ShareAccess,
    '    IN ULONG  OpenOptions
    '    );
    
    'File Open example:
        'ntret = ((NTCREATEFILE)(OldZwCreateFile))(&hfl, GENERIC_WRITE, &obja, &iosb, 0, FILE_ATTRIBUTE_NORMAL, 0, FILE_OPEN_IF, FILE_SYNCHRONOUS_IO_NONALERT, 0, 0); // FILE_OPEN
        'if(ntret != STATUS_SUCCESS) goto err;

  12. #12

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    General Declarations: (Part 2)
    Code:
    'Open File (Native API):
    Private Declare Function ZwOpenFile Lib "ntdll.dll" (ByRef FileHandle As Long, ByVal DesiredAccess As Long, ByRef ObjectAttributes As OBJECT_ATTRIBUTES, ByRef IoStatusBlock As IO_STATUS_BLOCK, ByVal ShareAccess As Long, ByVal OpenOptions As Long) As Long
    
    Private Declare Function NtOpenFile Lib "ntdll.dll" (ByRef FileHandle As Long, ByVal DesiredAccess As Long, ByRef ObjectAttributes As OBJECT_ATTRIBUTES, ByRef IoStatusBlock As IO_STATUS_BLOCK, ByVal ShareAccess As Long, ByVal OpenOptions As Long) As Long
    
        'DesiredAccess:
        Private Const GENERIC_ALL = 28
        Private Const FILE_ALL_ACCESS = 511
        
        Private Const SYNCHRONIZE As Long = &H100000
        Private Const GENERIC_READ As Long = &H80000000
        
        'ShareAccess:
        Private Const FILE_SHARE_READ = &H1
        Private Const FILE_SHARE_WRITE = &H2
        
        'OpenOptions:
        Private Const FILE_NON_DIRECTORY_FILE = 64
        Private Const FILE_DIRECTORY_FILE = 1
        Private Const FILE_SYNCHRONOUS_IO_NONALERT = 32
    
    'Open File (Regular):
    Private Declare Function OpenFile Lib "kernel32" (ByVal lpFileName As String, lpReOpenBuff As OFSTRUCT, ByVal wStyle As Long) As Long
        
        Private Const OFS_MAXPATHNAME = 128
        Private Const OF_READWRITE = 2
        
        Private Type OFSTRUCT
           cBytes      As Byte
           fFixedDisk  As Byte
           nErrCode    As Integer
           Reserved1   As Integer
           Reserved2   As Integer
           szPathName(0 To OFS_MAXPATHNAME - 1) As Byte '0-based
        End Type
    
    
    'File Information Class Type:
    Private Const FileNameInformation As Long = 9
        
    
    'Copy Memory:
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
    
    Private Declare Sub CopyMemoryPut Lib "kernel32" Alias "RtlMoveMemory" (ByVal Destination As Long, Source As Any, ByVal Length As Long)
    Private Declare Sub CopyMemoryRead Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, ByVal Source As Long, ByVal Length As Long)
    
    
    'Unicode String:
    Private Declare Sub RtlUnicodeStringToAnsiString Lib "ntdll.dll" (DestinationString As UNICODE_STRING, ByVal SourceString As Long, ByVal AllocateDestinationString As Boolean)
    Private Declare Sub RtlInitUnicodeString Lib "ntdll.dll" (DestinationString As UNICODE_STRING, ByVal SourceString As Long)

  13. #13

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    Events:
    Code:
    Private Sub Command1_Click()
        'Text2.Text = FormatFilePath(Text1.Text)
        Text2.Text = FormatFilePath2(Text1.Text)
    End Sub
    
    Private Function OpenFilePath(ByVal sPath As String) As String
    
        'Variables:
        Dim hFile As Long
        
        'Method 1:
            Dim OFS As OFSTRUCT
            hFile = OpenFile(sPath, OFS, OF_READWRITE)
        
        'Method 2:
            'Dim lReturn As Long
            'Dim tObjAttr As OBJECT_ATTRIBUTES
            'Dim tUString As UNICODE_STRING
        
            'Initialize attributes:
            'tUString.Length = Len(sPath) * 2
            'tUString.Buffer = StrPtr(sPath)
            
            'tObjAttr.Length = Len(tObjAttr)
            'tObjAttr.ObjectName = VarPtr(tUString)
            'tObjAttr.Attributes = OBJ_CASE_INSENSITIVE Or OBJ_INHERIT
            
            'Open File:
            'lReturn = ZwOpenFile(hFile, FILE_ALL_ACCESS, 0, tIO, FILE_SHARE_READ Or FILE_SHARE_WRITE, FILE_NON_DIRECTORY_FILE)
            'lReturn = NtOpenFile(hFile, GENERIC_READ Or SYNCHRONIZE, tObjAttr, tIO, FILE_SHARE_READ, FILE_NON_DIRECTORY_FILE Or FILE_SYNCHRONOUS_IO_NONALERT)
                'MsgBox GetSysMsg(lReturn0)
    
        'Return Value:
        OpenFilePath = hFile
    
    End Function
    
    
    Public Function FormatFilePath2(ByVal sPath As String) As String
    
        Dim tIO As IO_STATUS_BLOCK
        Dim tFileName As FILE_NAME_INFORMATION
        
        Dim hFile As Long
        Dim lReturn As Long
        
        '-----------
        
        'Open File:
        hFile = OpenFilePath(sPath)
            MsgBox "hFile  = " & hFile
            
        'Set buffer & size:
        tFileName.FileName.Length = Len(sPath) * 2
        tFileName.FileName.Buffer = StrPtr(sPath)
        Call RtlInitUnicodeString(tFileName.FileName, StrPtr(sPath))
        
            MsgBox "Unicode Buff = " & tFileName.FileName.Buffer
            MsgBox "Unicode Length = " & tFileName.FileName.Length
            MsgBox "Unicode MaxLength = " & tFileName.FileName.MaximumLength
        
        'Store structure size:
        Dim lSize As Long
        lSize = Len(tFileName)
            MsgBox "lSize = " & lSize
        
        'Set pointer:
        Dim ptr As Long
        ptr = VarPtr(tFileName)
            MsgBox "Pointer = " & ptr
            MsgBox "Pointer Size = " & Len(ptr)
        
        'Fill data structure:
        lReturn = NtQueryInformationFile(hFile, tIO, ptr, lSize, FileNameInformation)
            MsgBox GetSysMsg(lReturn)
        
        'Move pointer to variable:
        Dim tFNI As FNI
        
            'Init Unicode string maybe? (Still does not work)
            tFNI.FileName.Length = Len(sPath) * 2
            tFNI.FileName.Buffer = StrPtr(sPath)
            Call RtlInitUnicodeString(tFNI.FileName, StrPtr(sPath))
        
        'Call CopyMemory(tFNI, ByVal ptr, Len(ptr))
        'Call CopyMemory(ByVal VarPtr(tFNI), ByVal ptr, lSize)
        'Call CopyMemory(VarPtr(tFNI), ByVal ptr, Len(ptr))
        'Call CopyMemoryRead(ByVal VarPtr(tFNI), ByVal VarPtr(ptr), Len(ptr))
        
        Call CopyMemory(ByVal VarPtr(tFNI), ByVal ptr, LenB(tFNI))
        
        
            MsgBox "tFNI Size = " & Len(tFNI)
            
            MsgBox "Unicode Buff = " & tFNI.FileName.Buffer
            MsgBox "Unicode Length = " & tFNI.FileName.Length
            MsgBox "Unicode MaxLength = " & tFNI.FileName.MaximumLength
        
        Dim sValue As String
        sValue = Space(tFNI.FileName.Length \ 2)
            MsgBox "sValue Buff = " & sValue
        'Call CopyMemoryRead(sValue, ByVal tFNI.FileName.Buffer, (Len(tFNI.FileName.Buffer)))
        'Call CopyMemory(ByVal VarPtr(sValue), tFNI.FileName.Buffer, 4)
        Call CopyMemory(ByVal StrPtr(sValue), tFNI.FileName.Buffer, tFNI.FileName.Length)
            MsgBox "sValue = " & sValue
    
    End Function

    The problem is right here:
    Code:
        'Move pointer to variable:
        Dim tFNI As FNI
        
            'Init Unicode string maybe? (Still does not work)
            tFNI.FileName.Length = Len(sPath) * 2
            tFNI.FileName.Buffer = StrPtr(sPath)
            Call RtlInitUnicodeString(tFNI.FileName, StrPtr(sPath))
        
        'Call CopyMemory(tFNI, ByVal ptr, Len(ptr))
        'Call CopyMemory(ByVal VarPtr(tFNI), ByVal ptr, lSize)
        'Call CopyMemory(VarPtr(tFNI), ByVal ptr, Len(ptr))
        'Call CopyMemoryRead(ByVal VarPtr(tFNI), ByVal VarPtr(ptr), Len(ptr))
        
        Call CopyMemory(ByVal VarPtr(tFNI), ByVal ptr, LenB(tFNI))
    Notice how I tried the method you described in there.

    See if you have any idea why it does this. To create it just add it to a form and put 1 command button and 2 textboxes on it.

    Eneter a valid file path in textbox 1 and see what happens. It will go up to the point, the API will be successful, and then boom crashes.

    Please Help.


    OR

    Here I uploaded my code, just add a text file called A.txt to C:\ and click the command button and watch it crash right after the Error_Success Return from the API:
    http://www.mediafire.com/?7rzkn1ldywe

    So please help if you can.
    Last edited by altf4; Apr 29th, 2007 at 05:21 PM.

  14. #14
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: Help: Pointers Problems

    Like I said, you're making things way too complex. I am not even aware how to use that method that you are trying.

    Strings in VB, with respect to calling DLL functions, are somewhat strange. Internally, they're stored as Unicode. But when you call a DLL function and pass a String, it's converted to ANSI, and when the function returns, it's converted back to Unicode; a double waste of time.

    You can avoid this by writing your declarations using the Long data type instead of String. When you call the function, use the VB helper function StrPtr() to return a pointer to the string buffer itself. This way, you're letting the function access the actual Unicode string, rather than a converted copy of it.
    Bear in mind that most Win32 functions are only implemented in Unicode from Windows NT onwards. On systems running 95/98, the ANSI versions are generally the only ones available, unless the Microsoft Layer for Unicode is installed.

    To use a Unicode variant of a Win32 API function, change the suffix (in the Alias clause) from -A (ANSI) to -W (Wide).

    Using structures containing strings is just the same as passing strings on their own to a DLL function. If you pass the structure containing the strings then VB will convert them to ANSI. And again, just like declaring the function itself, you can declare the string parts of the structure As Long and store the value of StrPtr(mystring) in them. As long as the string exists in a variable (i.e. there is an actual reference to it in the code) the pointer returned by StrPtr will be valid.

    You should also note that many C functions have a out string parameters. C has no built-in string data type; there is no way for C functions to return a string as the actual return value. What most WinAPI functions do is return a success code, and write to string buffers that are passed in as parameters.
    This is different to using ByRef string parameters in VB itself, because the WinAPI functions don't know about VB's string type. A VB function can destroy, create, and resize existing string buffers, but a WinAPI function can't. You therefore need to create the buffer yourself and set it to the required size before calling the function. Most functions accept a length parameter for every out string parameter, so that they can limit the amount of data they write in order to avoid memory corruption. Some functions return a required buffer size, so that you can create the buffer and then call the function again (or another function) with the correct buffer size. You need to read the documentation for every function very carefully to get them all right.


    RtlMoveMemory (CopyMemory) can be used with strings, but it is not generally required; it is usually used in speed optimisation cases where you need to shift a block of string at once and using a loop would be inefficient.

    When you pass a variable to a DLL function by reference, you are allowing the function to alter it. This means that you are implicitly passing a pointer to that variable; since if you passed the variable itself, the function wouldn't know where to write to it.
    VarPtr() is used to obtain a (Long) pointer to a variable. However of course if you pass a pointer by reference you are actually passing a pointer to a pointer. (This may or may not be what you want, but 99% of the time it's not.)
    So therefore ByVal VarPtr(x) is equivalent to ByRef x.

    People tend to write all sorts of CopyMemory declarations for different types. In reality, you can do everything with just one:
    Code:
    Declare Sub RtlMoveMemory Lib "kernel32" ( _
      ByVal lpDest As Long, _
      ByVal lpSrc As Long, _
      ByVal cbLen As Long _
    )
    This declaration is actually the closest to the C version.

    To use it is very simple:
    Code:
    ' Copy the contents of variable b to variable a.
    
    Dim a As Long: a = 5760
    Dim b As Long: b = 12597
    
    RtlMoveMemory VarPtr(a), VarPtr(b), LenB(a)
    You should now (unless I really have forgotten everything about VB) be able to observe the value 12597 in variable a.

  15. #15

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    Hey thanks for the info. You seem to know a lot about the internals of windows and I am glad you explained that. It helped my bypass that problem.


    Now for the final step. I need to convert my unicode_string to a VB String.

    Now based on the info I have read on your article, and seeing some examples on the internet I dont see why this peice of code now crashes my vb. (Note this is a different problem than before. This is like #2.

    Ok here is the code:
    Code:
    Public Function FormatFilePath2(ByVal sPath As String) As String
    
        Dim tIO As IO_STATUS_BLOCK
        Dim tFileName As FILE_NAME_INFORMATION
        
        Dim hFile As Long
        Dim lReturn As Long
        
        '-----------
        
        'Open File:
            hFile = OpenFilePath(sPath)
                MsgBox "hFile  = " & hFile
            
        'Set buffer & size:
            tFileName.FileName.Length = Len(sPath) * 2
            tFileName.FileName.Buffer = StrPtr(sPath)
            Call RtlInitUnicodeString(tFileName.FileName, StrPtr(sPath))
        
                MsgBox "Unicode Buff = " & tFileName.FileName.Buffer
                MsgBox "Unicode Length = " & tFileName.FileName.Length
                MsgBox "Unicode MaxLength = " & tFileName.FileName.MaximumLength
        
        'Store structure size:
            Dim lSize As Long: lSize = Len(tFileName)
                MsgBox "lSize = " & lSize
        
        'Fill data structure:
            lReturn = NtQueryInformationFile(hFile, tIO, VarPtr(tFileName), lSize, FileNameInformation)
                MsgBox GetSysMsg(lReturn)
        
        'Move pointer to variable (not needed):
            'Dim tFNI As FNI
        
            'Call CopyMemory(ByVal VarPtr(tFNI), ByVal VarPtr(tFileName), LenB(tFNI))
            'Call RtlMoveMemory(ByVal VarPtr(tFNI), ByVal VarPtr(tFileName), LenB(tFNI))
        
            MsgBox "tFileName Size = " & Len(tFileName)
            
            MsgBox "Unicode Buff = " & tFileName.FileName.Buffer
            MsgBox "Unicode Length = " & tFileName.FileName.Length
            MsgBox "Unicode MaxLength = " & tFileName.FileName.MaximumLength
        
        'Return value:
        
            'Convert unicode to string:
            
                Dim sValue As String
                sValue = Space(tFileName.FileName.Length \ 2)
                    MsgBox "sValue Buff = " & sValue
            
                'Call CopyMemory(ByVal StrPtr(sValue), tFileName.FileName.Buffer, 4)
                'Call CopyMemory(ByVal StrPtr(sValue), tFileName.FileName.Buffer, LenB(sValue))
                'sValue = PtrStr(tFileName.FileName.Buffer)
                
                Call CopyMemory(ByVal StrPtr(sValue), ByVal tFileName.FileName.Buffer, tFileName.FileName.Length)
            
            
            'Return value:
                MsgBox "sValue = " & sValue
                FormatFilePath2 = sValue
        
    
    End Function

    Here is the block of code where the problem is created.
    Code:
        'Return value:
        
            'Convert unicode to string:
            
                Dim sValue As String
                sValue = Space(tFileName.FileName.Length \ 2)
                    MsgBox "sValue Buff = " & sValue
            
                'Call CopyMemory(ByVal StrPtr(sValue), tFileName.FileName.Buffer, 4)
                'Call CopyMemory(ByVal StrPtr(sValue), tFileName.FileName.Buffer, LenB(sValue))
                'sValue = PtrStr(tFileName.FileName.Buffer)
                
                Call CopyMemory(ByVal StrPtr(sValue), ByVal tFileName.FileName.Buffer, tFileName.FileName.Length)
            
            
            'Return value:
                MsgBox "sValue = " & sValue
                FormatFilePath2 = sValue

    Here is the exact line:
    Code:
    Call CopyMemory(ByVal StrPtr(sValue), ByVal tFileName.FileName.Buffer, tFileName.FileName.Length)
    That should work, shouldn't it? I dont see what is causing the crash.
    I hope you can help.

  16. #16
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: Help: Pointers Problems

    So, let me get this straight.

    You want to read the FileName from the FILE_NAME_INFORMATION structure returned by ZwQueryInformationFile?

  17. #17

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    Quote Originally Posted by penagate
    So, let me get this straight.

    You want to read the FileName from the FILE_NAME_INFORMATION structure returned by ZwQueryInformationFile?

    Exactly.

  18. #18
    PowerPoster
    Join Date
    Feb 2006
    Location
    East of NYC, USA
    Posts
    5,691

    Re: Help: Pointers Problems

    Quote Originally Posted by altf4
    Now based on the info I have read on your article, and seeing some examples on the internet I dont see why this peice of code now crashes my vb.
    Crashes with what error message? (Or is it just that VB has to close?)

    The usual problems when working with pointers and memory copying are 1) Not initializing a pointer (IOW the value of the pointer itself is zero) and 2) the size is wrong (or the destination isn't as large as the size you're giving [which is why you should always give the size of the destination, not the source]), causing VB to write part of the source into the next variable[1], causing an illegal or unwanted value which causes a crash somewhere down the line. And even if Murphy was a pessimist, the place the crash occurs usually has nothing to do with the error that caused it.

    [1]In memory, there's no separation between variables. If you declare an integer and 2 longs, VB marks a memory address as the address of the first byte of the integer, an address 2 bytes higher as the address of the first byte of the first long and an address 4 bytes higher as the address of the first byte of the second long.

    If you move a long to the integer, it gets written to the integer and the first 2 bytes of the first long - the API doesn't care what VB calls any of those addresses. Now when you pass the first long as a pointer, it has the wrong value and something crashes.
    The most difficult part of developing a program is understanding the problem.
    The second most difficult part is deciding how you're going to solve the problem.
    Actually writing the program (translating your solution into some computer language) is the easiest part.

    Please indent your code and use [HIGHLIGHT="VB"] [/HIGHLIGHT] tags around it to make it easier to read.

    Please Help Us To Save Ana

  19. #19

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    Hmm yea I have been trying many things with many combos, and nothing seems to get that value.

    if you can try downloading my code and see if you can figure it out.
    I debug it through msgboxs, so it should be pretty easy to see where it is at, or just press F8 and run it line by line.

    I just, cant seem to prevent vb from crashing by "Program encountered error... send... dont send,,, blah blah blah)

    So, to anyone, please post any code suggestions you have or think it might work or know it willl. I am open to w/e

    thanks.

  20. #20

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    Any Ideas?

  21. #21
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Help: Pointers Problems

    did you try what Penagate has suggested?
    you declare copymemory like this
    Code:
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
    but it should be declared like this
    Code:
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByVal Destination As long, ByVal Source As long, ByVal Length As Long)
    Then you should be able to use your code
    Code:
    Call CopyMemory(StrPtr(sValue), tFileName.FileName.Buffer, tFileName.FileName.Length)
    If that doesn't fix the problem then we'll continue to troubleshoot.

  22. #22

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    Quote Originally Posted by moeur
    did you try what Penagate has suggested?
    you declare copymemory like this
    Code:
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
    but it should be declared like this
    Code:
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByVal Destination As long, ByVal Source As long, ByVal Length As Long)
    Then you should be able to use your code
    Code:
    Call CopyMemory(StrPtr(sValue), tFileName.FileName.Buffer, tFileName.FileName.Length)
    If that doesn't fix the problem then we'll continue to troubleshoot.
    I am already passing the values ByVal in the actual code, so that shouldn't make a difference. But keep the suggestions coming.

  23. #23
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Help: Pointers Problems

    I'm saying Don't declare any parameters "as Any" as this only creates problems. Declare them all either "As Long" and pass by value or "As <specific type>" and pass by reference.

    Once you do this then your problems may go away. At least then we know that your declaration is not causing the problem and we can move on to the next possible cause.


  24. #24

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    Still seems to not work.

  25. #25

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    Here is the current code.

    Please help if you can.

    Edit: Old Code Removed... Solution Found.
    Last edited by altf4; Jul 7th, 2007 at 05:09 PM.

  26. #26

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    *Bump*

  27. #27
    Lively Member
    Join Date
    Jul 2007
    Posts
    98

    Re: Help: Pointers Problems

    Hei man,

    I work on VB and C++ around 5 years and as people wrote before me VB is not the language you have to use to try raping windows. It's super that you want to learn some useful functions, but try to belive me in a complicated program designed in VB API calls should be brought to minimum. The CopyMemory function is hard to use even in C++, so if you design an application that lies on this or other API core functions you have made an error at the first step.
    VB is easy, VB is fun but VB is not designed for complicated problemes including threading, synchronization, memory managment etc. Give it up and start C++.

  28. #28

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Location
    Home
    Posts
    85

    Re: Help: Pointers Problems

    Edit:
    Nevermind, I finally got it working.
    It had to do with how I was initializing object_attributes, the unicode_string and how the API function was setup.

    Finally. God. Took months jesus christ.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width