IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

PureBasic Discussion :

COMate - Contrôle des objets COM


Sujet :

PureBasic

  1. #1
    Responsable Purebasic

    Avatar de comtois
    Inscrit en
    Avril 2003
    Messages
    1 261
    Détails du profil
    Informations forums :
    Inscription : Avril 2003
    Messages : 1 261
    Points : 9 924
    Points
    9 924
    Billets dans le blog
    8
    Par défaut COMate - Contrôle des objets COM
    Mon anglais étant plus que douteux et limité, un coup de pouce pour traduire ce texte serait le bienvenue.

    Téléchargez COMate sur ce site : http://www.nxsoftware.com/

    L'auteur s'est basé sur le code open source DispHelper écrit en C, qu'il a converti en PureBasic. L'archive contient un fichier d'aide,les sources en PureBasic et le code source d'une vingtaine d'exemples (utilisation des OCX , ouverture d'une feuille excel et remplissage des cellules, etc ...)

    Pour vous mettre en appétit, voici un des exemples (il ouvre une feuille excel et écrit dans les cellules)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    ;/////////////////////////////////////////////////////////////////////////////////
    ;***COMate***  COM automation through iDispatch.
    ;*===========
    ;*
    ;*Excel demo.
    ;/////////////////////////////////////////////////////////////////////////////////
     
    IncludePath "..\"
    XIncludeFile "COMate.pbi"
     
     
    date$ = FormatDate("%dd/%mm/%yyyy", Date())
     
    Define.COMateObject ExcelObject, WorkBook
    ExcelObject = COMate_CreateObject("Excel.Application")
     
    If ExcelObject
      If ExcelObject\SetProperty("Visible = #True") = #S_OK
        WorkBook = ExcelObject\GetObjectProperty("Workbooks\Add")
        If WorkBook
          ExcelObject\SetProperty("Cells(1,1) = 'Hello'")
          ExcelObject\SetProperty("Cells(1,2) = 'from'")
          ExcelObject\SetProperty("Cells(1,3) = 'COMate!'")
          ExcelObject\SetProperty("Cells(1,5) = 'Today$0027s date is'")  ;$0027 is a hex escape code used to insert a ' (ascii 39) character.
          ExcelObject\SetProperty("Cells(1,6) = '" + date$ + "' AS DATE")
          ExcelObject\SetProperty("Cells(4,1) = 6.25")
          ;Retrieve a double value and a date.
            dbl.d = ExcelObject\GetRealProperty("Cells(4,1)")
              MessageRequester("COMate - Excel demo", "Result Cells(4,1) : " + StrD(dbl))
          ;For the date we retrieve it in string format.
            newDate$ = ExcelObject\GetStringProperty("Cells(1,6)")
              MessageRequester("COMate - Excel demo", "Result Cells(1,6) : " + newDate$)
          ExcelObject\Invoke("Quit()") 
          WorkBook\Release()
        EndIf
      EndIf
      ExcelObject\Release()
    Else
      MessageRequester("COMate -Excel demo", "Couldn't create the application object!")
    EndIf
    Hi,

    in association with ts-soft enterprises Wink I bring you COMate, a PB utility for controlling COM automation servers (components).

    Realising that a couple of projects I am working on will soon require to use some COM I decided to study OLE automation in depth, and the best way I found of doing this was to grab the open-source DispHelper library (written in c) and convert it to Purebasic. I have of course modified the library to suit my own ends!

    The main thing is that whilst the original DispHelper library uses a c-style Printf() syntax, my offering (COMate) uses what is, for me at least, a much more comfortable Visual Basic like syntax.

    Contrast :

    VB code :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    Dim excel As Object
    Set excel = CreateObject("Excel.Application")
    excel.Visible = blnTrue

    converted to Purebasic with the PureDispHelper library :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    Define.l ExcelApp
    ExcelApp = dhCreateObject("Excel.Application")
    dhPutValue(ExcelApp, ".Visible = %b", #True)

    and now converted to Purebasic with COMate :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    ExcelObject.COMateObject
    ExcelObject = COMate_CreateObject("Excel.Application")
    ExcelObject\SetProperty("Visible = #True")
    Features of COMate :

    * Completely free!
    * It comes in the form of a PB source code include file.
    * Ansi or Unicode and/or Threadsafe etc. (Well, as threadsafe as any COM components you may be controlling!)
    * An oop interface.
    * Method / property parameters are encoded in a very natural (VB) way within command strings.
    * Method/property calls can embed a chain of property-gets, each of which return a subobject etc. (all handled automatically by COMate).
    * Command strings can include escape characters in the form $xxxx where xxxx represents a 4 hexadecimal digit character code.
    * Easy enumeration of collections.
    * Automatic freeing of all strings (unlike DispHelper).
    * Full threaded error reporting. Each thread can report (if requested) the most recent COM error as well as a 'friendly' text description if appropriate. This means that if two threads are, for example, working on the same instance of a COM component, then the errors reported in one thread will not affect the other thread!



    I think you'd get a good feel for COMate (as well as the differences between this and DispHelper) by browsing the various demo programs which are mostly simple conversions of the PureDispHelper demo programs written by ts-soft, mk-soft and Kiffi; to whom I offer my thanks.

    COMate itself uses some code developed by ts-soft and he has been instrumental in helping me test COMate and indeed he translated some of the demo programs for use with COMate. ts-soft is thus very much a part of this project. Indeed, I would like to state right now that he is to be held responsible for any bugs!

    The COMate package includes the two source include files (one just has constants etc.) various demos and a very comprehensive CHM user manual. This manual is really the first place for those who have never used COM before.

    You can access the download through the nxSoftware site.

    ============================================
    Update - version 1.1.0. 6th Sept. 2008.
    My thanks to all those who have tested out the first version of COMate and to SFSxOI in particular for creating some nice WMI demos.

    Changes for this new version include :

    * Addition of a 'BYREF' parameter type-modifier. This is for calling methods (VB) in which certain parameters have been declared with the 'ByRef' modifier. For many COM objects it is not enough to simply pass the address of a variable, you will also need to use this new modifier. Particularly true for components created in VB.

    * COMate can now house ActiveX controls. See the demo programs and the help manual for details. I haven't added 'Event sinks' yet for trapping events/messages sent by such controls, but it is only a matter of time! Wink Consider this part to be in 'beta' stage because I took a slightly different approach here than PureDispHelper and so it remains to be seen whether more than just a handful of ActiveX controls will function correctly?

    * Have totally rewritten the command parser and various utility functions in order to increase the speed. DispHelper does not utilise such a parser and so will of course generally run faster. Increasing the speed has been accomplished by simply removing all PB string functions from the aforementioned functions and replacing with memory buffers and 'in place' alteration (via pointers) of strings. Tests on my machine of these functions (when stripped from COMate) show a x50 increase in speed. Take this with a pinch of salt though! It remains to be seen what effect (if any) these new routines will have, speed-wise, on COMate itself.
    This new version is now to be known as COMate-Turbo!

    * Have included a slightly modified version of mk-soft's / ts-soft's excellent 'VariantHelper' utility within the COMate-Turbo download, because there was a slight bug with the 'SafeArray' macros. Some COM methods/properties will return a SafeArray (yuk!) See the 'Demo_IPAddresses.pb' demo for an example of dealing with a return from a COM method in the form of a SafeArray.
    NOTE that the VariantHelper utility can only deal with SafeArray's of one dimension. Beyond this you are on your own!


    See the nxSoftware site for the download.

    =========================================
    Vous souhaitez participer à la rubrique PureBasic (tutoriels, FAQ, sources) ? Contactez-moi par MP.

  2. #2
    Responsable Purebasic

    Avatar de comtois
    Inscrit en
    Avril 2003
    Messages
    1 261
    Détails du profil
    Informations forums :
    Inscription : Avril 2003
    Messages : 1 261
    Points : 9 924
    Points
    9 924
    Billets dans le blog
    8
    Par défaut
    Nouvelle mise à jour disponible

    Update - version 1.1.1. 7th Sept. 2008.
    Apart from fixing the whole BYREF business which was completely flawed and ill thought out, I have plugged a major hole in COMate's supported parameter types, namely variants! Doh! Needless to say you can now pass variants by value or by reference (See Num3's Open Office example which is posted in this thread!)

    There are a couple of things to beware of with COMate parameters (and in particular when using BYREF) which I leave to the help manual (see the page on 'COMate command strings' for details).

    Finally, for those enaged with (or to ) WMI, there is a very very useful scripting utility which I came across which I have thrown into the COMate package and which should make things a lot easier!

    See the nxSoftware site for the download.

    Right, I'm off to study 'Event sinks' now... Let's hope I have more luck than I generally do with kitchen sinks!
    Et voici les exemples de Num3 mentionnés ci dessus :

    Code x : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    ;works with OpenOffice 2/3 and also with IBM Symphony (aka Open Office with less bugs) 
    XIncludeFile "COMate.pbi"
    XIncludeFile "VariantHelper_Include.pb"
    
    
    Procedure.s ConvertToUrl(strFile.s)
    strFile = ReplaceString(strFile, "\", "/")
    strFile = ReplaceString(strFile, ":", "|")
    strFile = ReplaceString(strFile, " ", "%20")
    strFile = "file:///" + strFile
    ProcedureReturn strFile
    EndProcedure
    
    
    Define.COMateObject oSM, oDesk, oDoc
    
    Define.safearray *openpar
    Define.variant openarray
    
    V_ARRAY_DISP(openarray) = safearray
    
    oSM = COMate_CreateObject("com.sun.star.ServiceManager")
    If oSM
      ;Creating instance of Desktop
        oDesk = oSM\GetObjectProperty("CreateInstance('com.sun.star.frame.Desktop')")
        If oDesk
          ;Opening a exisiting Document
            document.s = GetCurrentDirectory() + "test.odt"       
            oDoc = oDesk\GetObjectProperty("loadComponentFromURL('"+ConvertToUrl(document)+"', '_blank', 0, " + Str(openarray) + " as variant)")
           
            Debug COMate_GetLastErrorDescription()
           
          If oDoc
            oDoc\Release()
          EndIf
          oDesk\Release()   
        EndIf
      oSM\Release()
    EndIf

    Exemple pour ouvrir un document vide

    Code x : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    XIncludeFile "COMate.pbi"
    XIncludeFile "VariantHelper_Include.pb"
    
    
    Procedure.s ConvertToUrl(strFile.s)
    strFile = ReplaceString(strFile, "\", "/")
    strFile = ReplaceString(strFile, ":", "|")
    strFile = ReplaceString(strFile, " ", "%20")
    strFile = "file:///" + strFile
    ProcedureReturn strFile
    EndProcedure
    
    
    Define.COMateObject oSM, oDesk, oDoc
    
    Define.safearray *openpar
    Define.variant openarray
    
    V_ARRAY_DISP(openarray) = safearray
    
    oSM = COMate_CreateObject("com.sun.star.ServiceManager")
    If oSM
      ;Creating instance of Desktop
        oDesk = oSM\GetObjectProperty("CreateInstance('com.sun.star.frame.Desktop')")
        If oDesk
          ;Opening a new writer Document   
            oDoc = oDesk\GetObjectProperty("loadComponentFromURL('private:factory/swriter', '_blank', 0, " + Str(openarray) + " as variant)")     
          If oDoc
            oDoc\Release()
          EndIf
          oDesk\Release()   
        EndIf
      oSM\Release()
    EndIf
    Vous souhaitez participer à la rubrique PureBasic (tutoriels, FAQ, sources) ? Contactez-moi par MP.

  3. #3
    Responsable Purebasic

    Avatar de comtois
    Inscrit en
    Avril 2003
    Messages
    1 261
    Détails du profil
    Informations forums :
    Inscription : Avril 2003
    Messages : 1 261
    Points : 9 924
    Points
    9 924
    Billets dans le blog
    8
    Par défaut COMatePLUS remplace COMate
    Pour information COMatePLUS remplace COMate.
    C'est encore mieux. Vous pouvez le télécharger sur le site de l'auteur (gratuit).

    http://www.nxsoftware.com/

    L'archive contient pas mal d'exemples.

    Voici un exemple très court d'utilisation de COMatePLUS, ou comment faire parler votre ordi en quelques lignes de code.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
     
    ;/////////////////////////////////////////////////////////////////////////////////
    ;***COMate***  COM automation through iDispatch.
    ;*===========
    ;*
    ;*Sapi demo by ts-soft.
    ;/////////////////////////////////////////////////////////////////////////////////
     
    IncludePath "..\"
    XIncludeFile "COMatePLUS.pbi"
     
    EnableExplicit 
     
    Define.COMateObject obj = COMate_CreateObject("SAPI.SpVoice") 
     
    If obj 
      obj\Invoke("Speak('PureBasic, feel the pure Power')") 
      obj\Release() 
    EndIf

    COMatePLUS represents quite a jump forward over earlier versions of COMate, both in terms of it's internal workings and the facilities offered to the developer when working with automation servers. These changes were motivated by a desire to allow much faster access to COM methods/properties than was currently available through COMate's existing command processor.

    COMatePLUS can process 'strings' of 'closely related' method/property calls far far faster than earlier versions of COMate, although you do have to specifically make use of the new facilities in order to take advantage of any possible speed increases etc.

    Earlier versions of COMate, when given a command string as part of a method/property call, would first undertake the sometimes lengthy process of tokenising and parsing the command string looking for method calls, parameter types, type modifiers ...... etc. and only when this process was complete would it consider executing the COM method etc. When the COM method finished its work, the results of all that tokenising and parsing would be discarded, meaning that if the same method/property needed to be called again (perhaps with modified parameters) then the processing of the command string would need to be undertaken again!

    A somewhat wasteful affair don't you think? Smile


    COMatePLUS takes a different approach, one inspired by SQLite's use of 'prepared statements' etc.

    Basically, COMatePLUS allows you to pre-compile a command string right down to a level suitable for passing directly to a COM server. The result of this compilation is what I have termed a COMatePLUS statement which can be executed at any time and as many times (against different COMate objects if required) as required etc. Parameters can be altered between calls very quickly.

    The important thing is that the original COMateObject class now uses these pre-compiled statements 'behind the scenes' and so all existing COMate based code should run fine with COMatePLUS with no modifications whatsoever. Of course, all existing code will not run any faster; only code specifically making use of these prepared statements can benefit from these changes.


    A couple of newly added demo programs written to showcase COMatePLUS' prepared statements show a 10-fold increase in speed on my system, -something which is not to be sniffed at! Smile

    The following functions have been added by COMatePLUS for working with prepared statements (see the relevant sections of this manual for details) :

    1. COMate_PrepareStatement()
    2. COMate_GetStatementParameter()
    3. COMate_FreeStatementHandle()

    In addition, a new method has been added to the COMateObject class :

    GetCOMObject()

    which is, in a sense, the reverse of the COMate_WrapCOMObject() function.

    All of the COMateObject class methods dealing with calling COM methods/properties have also been modified by the addition of an optional parameter in which we can pass a COMatePLUS statement handle etc. See the COMateObject class section of this manual for details.


    Other alterations to the COMate library.

    You can now also opt to remove all error reporting from your COMatePLUS application. Simply define the constant #COMATE_NOERRORREPORTING = 1 at the top of your source, before including the main COMatePLUS source file.
    Et pour finir de vous convaincre de passer à COMatePLUS :

    In a sense, if the original COMate is to be considered as an interpreter (programming), then COMatePLUS is to be considered a compiler! Wink

    Whilst you work your way through the modifications to COMate, you may wonder why I have opted to implement certain features in the way I have? For example, take a look at the mechanism through which you modify parameters within a compiled statement! Here, you are required to deal directly with COM variant structures.

    All of these questions are addressed in the extensive modifications to the user manual and so I will not address them here. (All related to issues of speed and efficiency which is what these compiled statements are designed to enchance.)

    Needless to say that I advise even the most experienced COMate users to read the section on modifying statement parameters - and I mean every word! Smile There are some serious issues for you to consider and some potentially application wrecking pit-falls to avoid!

    In terms of speed gains, as stated above, only those applications designed to explicitly use pre-compiled statements will see any benefit and then only if the application is such that a compiled statement requires executing many times, -usually whilst modifying parameters etc.

    In my first test, I wrote a quick program to write 30000 cells to an Excel spreadsheet and found only moderate increases in speed etc. This is because Excel is slow at writing data and caches all write operations anyhow! The best way of quickly writing data to an Excel sheet is via a 2-dimensional safearray (thanks MrMat).

    My second very contrived test involved the VBScript regular expression object to which I applied 1 million string replacements.
    Without using pre-compiled statements the operation took around 65 seconds on my system to complete.
    Using compiled statements the same program took less than 6 seconds! 'nuff said!
    Vous souhaitez participer à la rubrique PureBasic (tutoriels, FAQ, sources) ? Contactez-moi par MP.

  4. #4
    Membre éprouvé

    Profil pro
    Inscrit en
    Mai 2005
    Messages
    279
    Détails du profil
    Informations personnelles :
    Âge : 39
    Localisation : France

    Informations forums :
    Inscription : Mai 2005
    Messages : 279
    Points : 1 179
    Points
    1 179
    Par défaut
    Quelle est la différence entre Comate et Comate Plus ?

  5. #5
    Responsable Purebasic

    Avatar de comtois
    Inscrit en
    Avril 2003
    Messages
    1 261
    Détails du profil
    Informations forums :
    Inscription : Avril 2003
    Messages : 1 261
    Points : 9 924
    Points
    9 924
    Billets dans le blog
    8
    Par défaut
    Je suis certain que tu lis l'anglais beaucoup mieux que moi

    En gros un gain en vitesse de x10 selon les applications.
    Vous souhaitez participer à la rubrique PureBasic (tutoriels, FAQ, sources) ? Contactez-moi par MP.

Discussions similaires

  1. cast avec des objets COM
    Par stardeath dans le forum Visual C++
    Réponses: 5
    Dernier message: 20/01/2010, 01h52
  2. Utilisation des objets COM
    Par jdelges dans le forum Général Dotnet
    Réponses: 1
    Dernier message: 26/01/2007, 23h52
  3. Comment débuguer des objets COM ?
    Par WebPac dans le forum Delphi
    Réponses: 5
    Dernier message: 14/10/2006, 19h28
  4. debugguer des objets COM
    Par alex181 dans le forum Delphi
    Réponses: 2
    Dernier message: 22/06/2006, 18h32
  5. [RPC] Appels distants : remplacer des objets COM
    Par pataguillon dans le forum C++
    Réponses: 26
    Dernier message: 30/03/2006, 09h17

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo