Срочно - стринги и вызов Win32 API функций
Релиб
Форумы       Участники    Календарь    Кто он-лайн?
Добро пожаловать, гость ( Вход | Регистрация )
        



Срочно - стринги и вызов Win32 API функций Expand / Collapse
Автор
Сообщение
20.04.2006 13:58


Supreme Being

Supreme BeingSupreme BeingSupreme BeingSupreme BeingSupreme BeingSupreme BeingSupreme BeingSupreme Being

участник
Last Login: 12.06.2007 20:05
Сообщ.: 279, Visits: 3 001
Я новичек в VB.NET.

В VB6 можно было декларировать стринг как

Dim strDirectory as String * 256

и потом передать в API функцию декларированную как

Private Declare Function FtpGetCurrentDirectory Lib "wininet.dll" Alias "FtpGetCurrentDirectoryA" ( _
ByVal hConnect As Integer, ByRef sCurrentDirectory As String, _
ByRef dwCurrentDirectory As Integer) As Boolean

после чего вызов выглядит как

FtpGetCurrentDirectory(hConnect, strDirectory, dwDirLen )


Теперь же, в .NET декларация функции выглядит так

Private Declare Function FtpGetCurrentDirectory Lib "wininet.dll" Alias "FtpGetCurrentDirectoryA" ( _
ByVal hConnect As Integer, ByVal sCurrentDirectory As System.Text.StringBuilder, _
ByRef dwCurrentDirectory As Integer) As Boolean

а вызов так

Dim strPath As String, dwCount As Integer = 1024, bRes As Boolean
Dim strBuilder As New System.Text.StringBuilder(dwCount)

If (Connected) Then
bRes = _FtpGetCurrentDirectory(m_hSession, strBuilder, dwCount)
If (bRes = False) Then
strPath = Nothing
Else
strPath = strBuilder.ToString()
End If

Else
strPath = Nothing
End If


Это более запутанно, но еще понятно. Но в следующем случае я не понимаю как мне декларировать структуру, чтобы вызов API был правильным:

Private Declare Function FtpFindFirstFile Lib "wininet.dll" Alias "FtpFindFirstFileA" ( _
ByVal hConnect As Integer, ByVal sSearchFile As String, _
ByRef findFileData As WIN32_FIND_DATA, ByVal dwFlags As Integer, _
ByVal dwContext As Integer) As Integer

Private Structure WIN32_FIND_DATA
Dim dwFileAttributes As Integer
Dim ftCreationTime As System.Runtime.InteropServices.ComTypes.FILETIME
Dim ftLastAccessTime As System.Runtime.InteropServices.ComTypes.FILETIME
Dim ftLastWriteTime As System.Runtime.InteropServices.ComTypes.FILETIME
Dim nFileSizeHigh As Integer
Dim nFileSizeLow As Integer
Dim dwReserved0 As Integer
Dim dwReserved1 As Integer
Dim cFileName As String
Dim cAlternateFileName As String
End Structure

...

Dim winFileData As WIN32_FIND_DATA, strFileName As String = Nothing
Dim hDirConnect As Integer

hDirConnect = FtpFindFirstFile(m_hSession, "", winFileData, 0, 0) <--- Здесь происходит ексепшион

Как я понял, проблема в декларации стрингов в структуре. Я пробовал декларировать их и как обычный стринг, и как
System.Text.StringBuilder, но ничего не помогает. (тип ошибок при различных декларациях разный, но результат тот же).

Вопрос: как в .NET декларируются структуры со стрингами для последующей передачи их в Win32 API функции для заполнения полей?
Сообщ. #895601
20.04.2006 16:52
Forum Guru

Forum GuruForum GuruForum GuruForum GuruForum GuruForum GuruForum GuruForum Guru

участник
Last Login: 21.04.2006 16:58
Сообщ.: 51, Visits: 573
А зачем через API? дот-нет имеет встроенные cредства доступа к FTP

/// MSDN

The .NET Framework provides comprehensive support for the FTP protocol with the FtpWebRequest and FtpWebResponse classes. These classes are derived from WebRequest and WebResponse. In most cases, the WebRequest and WebResponse classes provide all that is necessary to make the request, but if you need access to the FTP-specific features exposed as properties, you can typecast these classes to FtpWebRequest or FtpWebResponse.

Examples
For more information, see the following topics: How to: Download Files with FTP, How to: Upload Files with FTP, and How to: List Directory Contents with FTP.

Сообщ. #895620
20.04.2006 18:46


Supreme Being

Supreme BeingSupreme BeingSupreme BeingSupreme BeingSupreme BeingSupreme BeingSupreme BeingSupreme Being

участник
Last Login: 12.06.2007 20:05
Сообщ.: 279, Visits: 3 001
Это очень хорошо, что есть встроенная поддержка FTP, но:

1. Так как .Net не заменяет все функции WinAPI, то если не в этот раз, то в другой, я снова столкнусь с необходимостью получения инфы от виндов через структуры в которых могут быть стринги, и как мне их все же создавать и передавать?

2. Из просмотра топиков "How to: Download Files with FTP" и т.д. я не понял, а как мне передавать [bold]команды[/bold] например такую "siteside blksize 3096"? Мне необходимо подключаться через FTP к Mainfraim-у. А у него есть особые команды.

Хочу заметить, что приведенные топики дают примеры исползования на C#, а я его не знаю, да и VB.NET для меня тоже пока в новинку.
Сообщ. #895636
21.04.2006 17:11
Forum Guru

Forum GuruForum GuruForum GuruForum GuruForum GuruForum GuruForum GuruForum Guru

участник
Last Login: 21.04.2006 16:58
Сообщ.: 51, Visits: 573
В принципе ты прав. Но для того, в том числе, и создавался дотнет чтобы избежать использования вызовов API (за исключением выдающихся случаев).

Насчет как передать команду

///MSDN

The Method property determines which command is sent to the server. Typically, you set Method by using the strings defined in the WebRequestMethods.Ftp structure. When setting Method to UploadFile, you must do so before calling the GetRequestStream method. Failure to call these members in the correct order causes a ProtocolViolationException exception when you attempt to get the request stream.

The credentials supplied for the FtpWebRequest object must have permission to perform the specified method. If not, the FTP command fails.

You can set Method to any command recognized by the server and use the FtpWebRequest object to send the command. This works as expected only if the command does not require you to send data and the server does not send data in response to the request.

You must not send any command that alters the state of the connection. For example, do not use the "MODE", "PASV", or "PORT" commands. Using commands that change the state of the connection can leave the request and the underlying connection in an unusable state. To determine the success or failure of a command, check the Status and StatusDescription properties.

Может тебе стоит внимательно почитать там и разобрать предложенные примеры - в 90% случаев помогает.

И еще, где то на сайте MSDN валяется архив 101 VB.Net samples.
Скачай и знакомься с особенностями языка.

Работу с сетевыми потоками можно посмотреть в примере
Advanced .NET Framework (Networking) - Use Sockets
А в нем клиентскую часть.

Кстати, если ты четко понимаешь что и как передавать - можешь использовать его впрямую, просто поменяй открываемые порты (там используется 80(HTTP)).

Надеюсь, что помог.


Сообщ. #895706
10.05.2006 12:00


Supreme Being

Supreme BeingSupreme BeingSupreme BeingSupreme BeingSupreme BeingSupreme BeingSupreme BeingSupreme Being

участник
Last Login: 12.06.2007 20:05
Сообщ.: 279, Visits: 3 001
Ответ на первоначальный вопрос найден с помощью Messir-a.

Declare Function FtpFindFirstFile Lib "wininet.dll" _
   (ByVal hConnect As IntPtr, ByVal searchFile As String, _
   ByRef findFileData As WIN32_FIND_DATA, ByVal flags As Integer, _
   ByVal context As IntPtr) As IntPtr

<Serializable(), StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
    Structure WIN32_FIND_DATA
    Public dwFileAttributes As FileAttributes
    Public ftCreationTime As FILETIME
    Public ftLastAccessTime As FILETIME
    Public ftLastWriteTime As FILETIME
    Public nFileSizeHigh As Integer
    Public nFileSizeLow As Integer
    Public dwReserved0 As Integer
    Public dwReserved1 As Integer
    <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)> _
      Public cFileName As String
    <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=14)> _
        Public cAlternate As String
    End Structure

Ключевыми словами тут является декларирование стринга в структуре с маршализацией и указанием точного типа и размера стринга.

Сообщ. #896791
« пред. тема | след. тема »


Эту тему читают Expand / Collapse
Посетители: 0 (0 гостей, 0 участников, 0 скрыт.участников)
Сейчас нет участников, просматривающих тему.
Модераторы: Alexey, boombastik, bazile, pl, Alexey Spirin

Время GMT +3:00, Сейчас 11:00