Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Начинающим";
Текущий архив: 2013.03.22;
Скачать: [xml.tar.bz2];

Вниз

Перевести код из VBA в Pascal   Найти похожие ветки 

 
_Mik   (2012-08-10 14:31) [0]

Народ, помогите плиз, не выходит перевести код из VBA в Паскаль:

VBA

Declare Function ODMRegisterApp Lib "odma32.dll" (ODMHandle As Any, ByVal Version As Integer, ByVal AppID As String, ByVal EnvData As Long, Reserved As Any) As Integer
Declare Function ODMOpenDoc Lib "odma32.dll" (ByVal ODMHandle As Any, ByVal flags As Long, ByVal Docid As String, ByVal DocLocation As String) As Integer

...
Dim buffer As String * 255         " Fixed buffer for passing strings to C-type routines
Dim Docid As String
Dim DocLocation As String          " regular VB variant string
Dim DocTitle As String
Dim rc As Integer          " result code
Dim SearchNames As Name

   Call MsgBox("DDEOpen (" + ODMADocID$ + "," + Str(flags))
   On Error GoTo EndOpenDocument

   rc = 0

   ODMHandle = ODMA.RegisterAppWithODMA
 
   buffer = Space(Len(buffer))
   Docid = ODMADocID$
   
   " User selected a document, so open it through ODMA
   rc = ODMA.ODMOpenDoc(ODMHandle, flags, Docid, ByVal buffer)
...

Pascal

interface
   function ODMRegisterApp (var ODMHandle: variant ;Version : Integer; AppID : String;var  EnvData : LongWord; Reserved: variant): Integer; stdcall; external "odma32.dll";
   function ODMOpenDoc     (var ODMHandle: variant ;var flags   : Integer; Docid : String; var  DocLocation : shortstring): Integer; stdcall; external "odma32.dll";

   Procedure test();

   //====================================================
   //
   const ExcelAppID = "MS EXCEL";
   const ODM_API_VERSION = 100  ;                        // версия API_DM

   // флаги доступа
   const ODM_VIEWMODE=2;                                 // только для чтения

implementation

uses
 Classes, SysUtils, windows;

Procedure test();
var
   result        : integer ;
   ODMHandle     : variant ;
   Handle        : HWND    ;
   DocFilePath   : shortstring  ;
   Docid         : string  ;
   viewMode      : integer ;

begin
   Docid :="::ODMA\PCDOCS\VLGDMLIB\156276\1";
   viewMode:=ODM_VIEWMODE;

   Handle:= GetForegroundWindow ;
   result:= ODMRegisterApp (ODMHandle, ODM_API_VERSION,  ExcelAppID, Handle, nil );
   result:= ODMOpenDoc     (ODMHandle, viewMode, Docid , DocFilePath );
end;

При запуске ODMOpenDoc  возникает исключение!


 
Anatoly Podgoretsky ©   (2012-08-10 15:04) [1]

> _Mik  (10.08.2012 14:31:00)  [0]

Так и пишет - я исключение?


 
_Mik   (2012-08-10 15:28) [2]

Проект dmConsole вызвал класс исключения "external:SIGSEGV"
по адресу 10003092


 
Dimka Maslov ©   (2012-08-10 21:11) [3]

String это исключительно делфийская сущность. Надо использовать array[0..255] of Char. Так же вместо variant нужен OleVariant. Также надо разобраться, где var, a где не var. Хорошо бы ещё поискать родной сишный заголовочный файл.


 
turbouser ©   (2012-08-10 22:04) [4]

function ODMRegisterApp (var ODMHandle: variant ;Version : Integer; AppID : PChar;var  EnvData : LongWord; Reserved: variant): Integer; stdcall; external "odma32.dll";
  function ODMOpenDoc     (var ODMHandle: variant ;var flags   : Integer; Docid : PChar; var  DocLocation : PChar): Integer; stdcall; external "odma32.dll";
Как-то так.


 
turbouser ©   (2012-08-10 22:08) [5]


>  Dimka Maslov ©   (10.08.12 21:11) [3]

+1


 
_Mik   (2012-08-11 17:03) [6]

Спасибо в понедельник попробую, вся фишка в том, что это не моя библиотека, и она является частью документа оборота работающего на работе...


 
_Mik   (2012-08-13 14:09) [7]

Ничего не выходит, первая функция выполняется нормально в таком виде:

function ODMRegisterApp (var ODMHandle: variant ;Version : Integer; AppID : String;var  EnvData : LongWord; Reserved: variant): Integer; stdcall; external  "odma32.dll";
   


А вторая все так же выдает исключение, к сожалению исходники на VBA это все, что у меня есть...
OleVarriant вроде как не нужен...
Если можно по подробней про array[0..255] of Char, дельфи не занимался уже 5 лет, вспоминать трудно...


 
_Mik   (2012-08-13 14:11) [8]

Забыл сказать, пишу под Lasarus, oleVariant вызывает такое же исключение, вернулся к Variant


 
_Mik   (2012-08-13 14:16) [9]

Сделал так:

type
  tSyzeArr =  array[0..255] of Char ;

   function ODMRegisterApp (var ODMHandle: variant ;Version : Integer; AppID : String;var  EnvData : LongWord; Reserved: variant): Integer; stdcall; external  "odma32.dll";
   function ODMOpenDoc     (var ODMHandle: variant ;var flags : Integer; Docid : String; var  DocLocation : tSyzeArr): Integer; stdcall; external "odma32.dll";

         
...

Procedure test();
var
   result        : integer ;
   ODMHandle     : variant ;
   Handle        : HWND    ;
   DocLocation   : tSyzeArr; //array[0..255] of Char   ;
   Docid         : PChar  ;
   viewMode      : integer ;

begin
   Docid :="::ODMA\PCDOCS\VLGDMLIB\155628\1";
   viewMode:=ODM_VIEWMODE;
   //SetLength (DocFilePath, 255);

   Handle:= GetForegroundWindow ;
   result:= ODMRegisterApp (ODMHandle, ODM_API_VERSION,  AppID, Handle, nil );
   result:= ODMOpenDoc     (ODMHandle, viewMode, Docid , DocLocation);
end;        

функция
ODMOpenDoc    выдает туже ошибку


 
sniknik ©   (2012-08-13 16:30) [10]

вообще то
> rc = ODMA.ODMOpenDoc(
в бейсике (куске любезно тобой обрезанном так что не разобрать... ) выглядит как вызов функции обьекта/COM объекта, а у тебя попытка связывания как регулярной процедуры... ну, даже если они экспортируются, то как с данными объекта? т.е. в дельфевых терминах это классовая функция, или нет, чтобы было возможно.


 
_Mik   (2012-08-13 16:51) [11]

rc это целая переменная , которая указывает на результат выполнения,
если rc=0 то ошибок нет


 
_Mik   (2012-08-13 16:55) [12]

В результате вызова
result:= ODMOpenDoc     (ODMHandle, viewMode, Docid , DocLocation);
переменная result должна быть равна 0
а DocLocation содержать путь к файлу, на диске ...
viewMode = 2  - целое
Docid  содержит строку, которая указывает путь к файлу в системе документооборота...


 
_Mik   (2012-08-13 22:58) [13]

А com/activex даже и не пахнет, мало того программа написана на vba, по этому и нормальным ООП там не пахнет...


 
Германн ©   (2012-08-14 02:00) [14]


>  _Mik   (13.08.12 22:58) [13]
>
> А com/activex даже и не пахнет, мало того программа написана
> на vba

А что такое по вашему VBA?


 
sniknik ©   (2012-08-14 08:21) [15]

не обманывай себя, если ты чего то не знаешь это не значит что этого "не бывает".

но вообще, не пахнет так не пахнет, ищи ошибку дальше там где искал.


 
_Mik   (2012-08-14 09:58) [16]

Просто вся суть этого действа сводиться к заказу файла из документооборота и получение пути к нему на диске, что и делает 2 функция...

С ком и активХ я работал, например я писал макрос работы с автокадом из екселя, и наборот...

Спасибо за советы, попробую пере компилировать в дельфи...


 
_Mik   (2012-08-14 16:36) [17]

Нашел описание:
ODMOpenDoc

ODMSTATUS ODMOpenDoc( ODMHANDLE handle, DWORD flags, LPSTR lpszDocId, LPSTR lpszDocLocation )

This function causes the DMS to make a document available to the application.  It performs any necessary pre-processing (mapping network drives, checking security, etc.) and then returns to the application a temporary filename that can be used to access the document during the current session.  Note that this function does not open the document file; it merely makes the file temporarily available to the calling application.  The application can then open, read, write and close the file as needed.

If ODM_MODIFYMODE is requested, the DMS may refuse the request if the user has view-only rights (ODM_E_ACCESS) or if the document is currently checked-out (ODM_E_INUSE) to another user.  It is recommended that the application retry the request specifying ODM_VIEWMODE in both cases so that the user can at least view the document and possibly save changes to a new document.

Applications are encouraged to give the user the same level of feedback if a DMS based document is opened for read-only access as they would for a document based in the platform’s native file system.

When the application is finished using a file which was opened with either ODM_MODIFYMODE or ODM_VIEWMODE it must call ODMCloseDoc or ODMCloseDocEx.  When an application is finished using a file that was obtained with the  ODM_REFCOPY option it does not have to call ODMCloseDoc or ODMCloseDocEx, however, it must delete the temporary file.

If an application has opened a document in ODM_VIEWMODE and wishes to switch to ODM_MODIFYMODE, it must first call ODMCloseDoc or ODMCloseDocEx then call ODMOpenDoc requesting ODM_MODIFYMODE.  The same is true if the application wishes to switch from ODM_MODIFYMODE to ODM_VIEWMODE.  The ODM_E_ALREADYOPENED error status is returned by the DMS if the application attempts to re-open a document that it has already opened in either of these two modes.

Parameters:

handle - in - A handle obtained by a previous ODMRegisterApp call.

flags - in - One or more of the following flags:

ODM_MODIFYMODE - The DMS should make the document available in a modifiable mode.  This mode is assumed if ODM_VIEWMODE or ODM_REFCOPY is not explicitly requested.

ODM_VIEWMODE - The DMS should make the document available in a view-only mode.  Any changes made to the document will not be transferred back to the document repository.  If ODM_VIEWMODE and ODM_MODIFYMODE are both specified in the same call the ODM_E_INVARG error will be returned.

ODM_REFCOPY - The DMS should make a read-only reference copy of the document available to the calling application.  The DMS must return a different filespec in lpszDocLocation each time this function is called.  It is invalid to specify ODM_REFCOPY with either ODM_VIEWMODE or ODM_MODIFYMODE.  The calling application must delete any reference copy file obtained using this option and it should not call ODMCloseDoc or ODMCloseDocEx.

ODM_SILENT - The DMS should not require user interaction while satisfying the call.  If the call cannot be satisfied without user interaction then an error should be returned.

lpszDocId - in - A document ID.  This is typically obtained by a call to ODMSelectDoc or ODMNewDoc.

lpszDocLocation - out - A pointer to a buffer of at least ODM_FILENAME_MAX bytes in length.  The DMS will store in this buffer a null-terminated string indicating where the caller can access the document during the current session.  Typically, this will be the full path/file name of the specified document, but some document formats may dictate another type of location such as a directory name.  If an error occurs then the contents of the buffer will be undefined.

Return value:  

ODM_SUCCESS if successful.
ODM_E_ACCESS if the user does not have the access rights requested (for example, modify mode was requested but the user only has view rights to the document).
ODM_E_INUSE if the user is currently unable to access the document in modify mode because it is checked-out by another user.  This differs from ODM_E_ACCESS in that it is expected that the user might be able to access the document in the specified mode at some point in the future.
ODM_E_DOCID if the document ID is invalid or refers to a document that no longer exists.
ODM_E_OFFLINE if the DMS cannot currently access the document because the user client is off-line.
ODM_E_ARCHIVED if the DMS cannot currently supply the document content because it has been archived.
ODM_E_USERINT if the ODM_SILENT flag was specified and the DMS could not make the specified document available without user interaction.
ODM_E_INVARG if both ODM_OPENMODE and ODM_VIEWMODE have been specified or if either of those modes was specified with ODM_REFCOPY.
ODM_E_ALREADYOPENED if the application attempts to reopen a document with ODM_MODIFYMODE or ODM_VIEWMODE that it has already opened with either of these modes.  See below for one possible exception.
ODM_E_FAIL if the DMS is unable to make the document accessible for any other reason.
ODM_E_HANDLE if handle was invalid.

If the application attempts to open a document for ODM_VIEWMODE that it already has opened for ODM_VIEWMODE, then the DMS may either return the ODM_E_ALREADYOPNED error status or ODM_SUCCESS along with the previously returned temporary file specification.  The DMS should not return ODM_SUCCESS in this case unless it is maintaining a reference count of the number of times this application has opened the document for ODM_VIEWMODE access.  The application must call ODMCloseDoc or ODMCloseDocEx once for every time the document was successfully opened.  On the last close call the DMS will delete the temporary file.


 
_Mik   (2012-08-14 16:37) [18]

Исправил код так:



....

function ODMRegisterApp (var ODMHandle: HWND ;Version : Integer; AppID : LPSTR;var  EnvData : HWND; Reserved: Pointer ): Integer; stdcall; external  "odma32.dll";
 function ODMOpenDoc     (var ODMHandle: HWND ;var flags : DWORD ; Docid : LPSTR;var DocLocation : LPSTR): Integer; stdcall; external "odma32.dll";

 function ODMActivate    (ODMHANDLE: HWND; action: WORD ;lpszDocId:LPSTR ): Integer; stdcall; external "odma32.dll";

var
 Form1: TForm1;

implementation

{$R *.dfm}
   const AppID = "EXCEL";
   const ODM_API_VERSION = 200  ;
   const ODM_VIEWMODE=2;

procedure TForm1.Button1Click(Sender: TObject);
var
   res           : integer ;
   ODMHandle     : HWND; //OlEVariant ;
   WndHandle     : HWND    ;
   DocLocation   : LPSTR;//; //PChar; //array[0..255] of Char   ;
   Docid         : LPSTR  ;
   viewMode      : DWORD  ;

begin
   Docid :="::ODMA\PCDOCS\VLGDMLIB\157713\1";
   viewMode:=ODM_VIEWMODE;
   //SetLength (DocLocation, 255);

   WndHandle:= form1.Handle;
   try
     GetMem ( DocLocation, 256);
    // new (DocLocation);
     res:= ODMRegisterApp (ODMHandle, ODM_API_VERSION,  AppID, WndHandle, nil );
   //  res:= ODMActivate    (ODMHandle, 2, Docid);
     res:= ODMOpenDoc     (ODMHandle, viewMode, Docid , DocLocation);

   finally
     FreeMem (DocLocation);
    // Dispose   (DocLocation);
   end;

   res:=res+1;
   form1.Caption:=intToStr (res);
end;

end.


в дельфи на ODMOpenDoc   выдает accses violation at adress 01153873 write of adress 0026ED5D

остальные функции вроде как работают, этажа функция из VBa вызывается нормально... ((((


 
ProgRAMmer Dimonych ©   (2012-08-14 16:42) [19]

На какой строке валится? Уж не стековый ли адрес этот 0026ED5D?


 
turbouser ©   (2012-08-14 16:57) [20]

DocLocation   : array[0..ODM_FILENAME_MAX] of Char


 
sniknik ©   (2012-08-14 17:17) [21]

LPSTR = PChar


 
sniknik ©   (2012-08-14 17:19) [22]

> Исправил код так:
> function ODMOpenDoc     (var ODMHandle: HWND ;var flags : DWORD ; Docid : LPSTR;var DocLocation : LPSTR): Integer; stdcall; external "odma32.dll";
по
> Нашел описание:
есть разница


 
_Mik   (2012-08-14 21:18) [23]

спасибо завтра еще раз попробую


 
_Mik   (2012-08-15 08:45) [24]

Все бестолку, DocLocation   : array[0..ODM_FILENAME_MAX] of Char тоже не помогает...


 
sniknik ©   (2012-08-15 10:17) [25]

и не должен если в определении проблема. ты вообще понимаешь, что значит var в определении? видимо нет, если одинаковые в "найденом"/бейсике определенные параметры у тебя описаны по разному.


 
_Mik   (2012-08-15 13:05) [26]

такой параметр может быть изменен внутри функции, и будет возвращен в вызываемый код...


 
_Mik   (2012-08-15 13:12) [27]

Спасибо большое, я разобрался! Благодаря Вам!

function ODMOpenDoc     (ODMHandle: HWND ;flags : DWORD ;Docid : LPSTR;DocLocation : LPSTR): Integer; stdcall; external "odma32.dll";

Var там и не нужен был, LPSTR это же указатели...



Страницы: 1 вся ветка

Форум: "Начинающим";
Текущий архив: 2013.03.22;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.54 MB
Время: 0.082 c
15-1338529424
alexdn
2012-06-01 09:43
2013.03.22
Куда выложить


2-1329812260
jacksotnik
2012-02-21 12:17
2013.03.22
Маска ввода


15-1351936374
xayam
2012-11-03 13:52
2013.03.22
Google App Engine (GAE)


15-1331817337
QWERTY_
2012-03-15 17:15
2013.03.22
thumbnails


4-1261510346
denis_l
2009-12-22 22:32
2013.03.22
Определение пользователя который запустил процесс





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский