рефераты конспекты курсовые дипломные лекции шпоры

Реферат Курсовая Конспект

MyComObject ENDS

MyComObject ENDS - раздел Образование, Creating a COM object in ASM   The First Point Is I Have Great Latitude In Defining This Str...

 

The first point is I have great latitude in defining this structure. The only element that the COM contract imposes on it is that it contain a DWORD pointer to the vtable of functions. I also use it to hold the private data for each interface, that being the reference counts and values. nValue is the Value the MyCom interface works with, as we will see next. The dynamic memory for these structures is allocated with the API function CoTaskMemAlloc and released with CoTaskMemFree. These are exported by the ole32.dll, which has many other useful exports, such as checking for GUID equality, and converting GUIDs to and from character strings.

 

MyCom, a Simple Interface

---------------------------------------------------------------------------------------------------------------------To illustrate the workings of COM interface, we will create a simple interface called IMyCom (all interfaces in COM should have the "I" prefix, for Interface). This interface, like all COM interfaces, derives from IUnknown. This simple means its first three functions are QueryInterface, AddRef, and Release.

 

To add our custom interface members, we add the next three function members (in C styled prototypes):

 

HRESULT SetValue(long *pVal);

HRESULT GetValue(long newVal);

HRESULT RaiseValue(long newVal);

 

These functions allow us to check the functionality of our interface. SetValue and GetValue allow us to set and read a data member of our interface. RaiseValue is a member function that adds a value to this data. Thus, we can assure ourselves we really are accessing a fully functional object from VB.

 

These structures in memory look like this:

 

 

The client just holds a pointer (ppv) to this distributed structure. (The generic name for the ppv pointer comes from it's C++ definition of "pointer to pointer to (void).") The "object" data blob is dynamically allocated and initiated when we create instance the class. The vtable and the server functions are static, they are defined at compilation time.

 

One point to notice here is the vtable holds pointers to the functions, not the functions themselves. Thus, we can "override" an inherited function simply by changing what routine the vtable points to. I have to say "override" in quotes because the class definitions are just a mental concept in this ASM implementation, I did not write classes and inherit them in other classes. But the concept is the same.

 

In the example to follow, there are function "overrides" performed this way. The IClassFactory and IMyCom both inherit QueryInterface from IUnknown. But as they support different interfaces, they need different routines to return different results. Thus, there are two QueryInterface routines (QueryInterfaceCF and QueryInterfaceMC) pointed to from the different vtables.

 

For simplicity, the AddRef and Release are also customized as to which interface they support. This is not an issue with AddRef, but the Release functions differ in that the MyCom Release has to know how to destroy the MyCom object. A further refinement for the future is to declare all objects in the same way so the same function can delete them, and we could use a single implementation of Release for everything.

 

A minor point on calling COM interfaces from within the server: There is entirely no reason to go through the object table to get the pointer to a member function: INSIDE the server it's just another function, you can invoke it directly, as the code knows exactly where it is at compile time. Just think of it as an advanced optimization technique. This works because the calls all contain THIS (the object pointer) as a parameter, and hence answer the question "which" object with "THIS" object.

 

Another minor point here, each time a client makes a call on our object, it walks through memory from ppv to pv to the vtable to get the address of the function to invoke. Should you want to, you may change this final pointer during the object's lifetime to make it exhibit different characteristics. There is nothing in the COM contract to prohibit it, though it is akin to self-modifying code. I only mention it because previous writings claimed this not to be true.

 

 

Type Libraries

---------------------------------------------------------------------------------------------------------------------On WinTel platforms, every COM interface gets information on it stored in the system registry. These interfaces are created in something called "Interface Definition Language" (IDL) that may be compiled by MIDL (Microsoft Interface Definition Language) compiler, a command line app. I'm not going to pretend to you I fully understand IDL well enough to sit down in Notepad and define interfaces. But, since the MIDL tool is only shipped with MSVC, if you have it then you have VC, so I used the Visual Studio tool to create my original interface definition file.

 

I started an ATL project named MyComApp, and insert a new ATL object and choose Simple Object named MyCom (the same terms my app will use). The class wizard then created a blank IMyCom interface. The ATL Attributes need to be set to Single Thread, Custom Interface, and No Aggregation. Then I created the interface by right clicking the IMyCom interface in the Class browser, and using Add Property to insert the SetValue, GetValue properties, and RaiseValue method. Then I saved and closed the app and copied the MyComApp.idl file to my assembly program folder.

 

Here is the output of the VC ATL interface definition file (.idl):

 

– Конец работы –

Эта тема принадлежит разделу:

Creating a COM object in ASM

aggregate REFIID riid... Reference to the interface identifier... Oid ppvObject Address of output variable that receives...

Если Вам нужно дополнительный материал на эту тему, или Вы не нашли то, что искали, рекомендуем воспользоваться поиском по нашей базе работ: MyComObject ENDS

Что будем делать с полученным материалом:

Если этот материал оказался полезным ля Вас, Вы можете сохранить его на свою страничку в социальных сетях:

Все темы данного раздела:

Creating a COM object in ASM
  Copyright © Dec 27, 2000 by Ernest Murphy ernie@surfree.com For educational use only. All commercial use only by written license.   Revised December

Increments or decrements the lock count
  LockServer keeps the class factory instanced (helpful if one has to make numerous object copies). CreateInstance is the workhorse here, it is used to creates the object's "work

Interface IMyCom : IUnknown
{ [propget, helpstring("property Value")] HRESULT Value([out, retval] long *pVal); [propput, helpstri

Coclass MyCom
{ [default] interface IMyCom; }; };     This file can be used as

RaiseValue PROTO :DWORD, :DWORD
  BIG difference... but for a simple reason. Interfaces written for type libraries are as general as can be, and are directed at clients such as Visual Basic, and VB is designed to ho

Typelib MyCom.tlb
  Making it the first resource element is important, as later on we will be using the LoadTypeLib API function to extract this library, and this function expects to find the library a

HKEY_CLASSES_ROOTTypeLib{A21A8C42-1266-11D4-A324-0040F6D487D9}1.0HELPDIR
(Default) "C:masm32COMMyCom"   One key value here is variable, that is the path and name of the server dll itself. On my system I placed it at &quo

AddRef_MC endp
  AddRef is a bit unusual in that it does not return a HRESULT (failure code), instead it returns the object count. The return value is undefined in the COM contract, but it is tradit

RaiseValue ENDP
    MyCom.dll, the server code ---------------------------------------------------------------------------------------------------------------------To build the

End Sub
  Now you can run the application and test the server by clicking the Raise button. Do be careful, there is no error checking to see if you put a valid number in Text2. What you are s

Хотите получать на электронную почту самые свежие новости?
Education Insider Sample
Подпишитесь на Нашу рассылку
Наша политика приватности обеспечивает 100% безопасность и анонимность Ваших E-Mail
Реклама
Соответствующий теме материал
  • Похожее
  • Популярное
  • Облако тегов
  • Здесь
  • Временно
  • Пусто
Теги