ATL-JavaScript Mixed Programming
JavaScript hybrid programming-ATL
Last update date:
Environment:Windows 8.1 64bit English version, Visual Studio 2013 Professional Update1 English version
Prerequisites:Basic concepts of COM
Author:Kagula
Introduction
ATL (ActiveTemplate Library) is a set of C ++ templates provided by Microsoft to simplify COM programming. This section describes how to use ATL to create a simple lightweight COM Service for JavaScript scripts to call, so that we have a concept for the use of ATL.
Hello, World
Use the Administrator account to start Visual Studio. Otherwise, COM Service registration fails.
Name the new Solution as ATLTutorial1, [VisualC ++]-> [ATL Project]-> [Application type: select Dynamic LinkLibrary (DLL)]-> [Support options: select Allow merging of proxy/stubcode]-> [Finish] to create a COM Service Program.
[Allow merging of proxy/stub code] option, all your components (Binary code) will be packaged into a DLL file, proxy/stub refers to proxy and stub.
You also need to add COM Class for the COM Service, in the [Class View] window, right-click the project name [ATLTutorial1]-> [Add]-> [Class]. In the displayed window, select [ATL]-> [ATLSimple Object] To start ATL Simple object wizard, enter HelloWorld in short name, select Apartment In Threading model, select No for Aggregation, Dual for Interface, and Connection Points and IObjectWithSite (IE object Support) for support to create a HelloWorld class.
This wizard [1] exposes your HelloWorld class in the IDL file, [2] creating an IHelloWorld class to define your HelloWorld interface [3] creating a CHelloWorld class, implement the functions you define in the IHelloWorld interface. In an external client program, your class is instantiated through the uuid value of the HelloWorld class in the IDL file.
Interface Options
The Dual option of the Interface allows your Class to inherit the IDispatch Interface and custom Interface (CustomInterface). Dual is the meaning of the Dual Interface. IDispatch is an interface exposed by OLE Automation protocol. The Automation (IDispatch) interface allows the client program to find out the attributes and methods supported by the COM object during running, and provides necessary information on how to call the COM Object Attributes and methods. Because the client program does not need to know the COM Object member during compilation, the Script program, for example, the Java Script running on IE (Internet Explorer), can call your COM object. The custom interface enables the client program to call your object based on VTABLE, which is less costly than the call Performance Based on IDispatch. It is a lollipop of the IDispatch interface.
Threading Model)
The core of COM is to give the customer program the details of the hide object as much as possible. The customer program only needs to know how to call the COM Object. One of the details Of hide is whether the COM object is thread-safe, so Microsoft defines the concept of Apartment to simplify this detail.
ThreadingModel Apartment defines the execution context of the COM Object. A root thread in the client program calls CoInitializa (or CoInitializeEx or OleInitialize) to enter the Apartment) initialize the COM Object in (all. COM requires the customer to call the methods in the COM object through the interface pointer, which must be performed in Apartment. In other words, to call a COM object from the current thread, you must first initialize the COM Object using the CoCreateInstance method. CoCreateInstance will create an Apartment based on the Threading Model attribute of your object. An Apartment can contain any number of COM objects.
COM defines two types of Apartment, Single-threaded apartment STA (Single-threadedapartment) and multi-threaded Apartment MTA (multi-threaded apartment ).
Stas only allows one thread to access your COM object, so it is thread-safe. Therefore, the method of your COM object will not be accessed by multiple threads at the same time, A single process can have multiple single-threaded apartments (Stas). The data stored in the Stas can only be accessed by a single thread.
MTA allows multi-threaded access to your COM object, but only one multi-threaded apartment (MTA) can be contained in a process. The data stored in it will be called by multiple threads.
Threading Model(Thread model)Select the Apartment option to indicate that our COM object is thread unsafe and must be called in the thread that initializes it. The system will provide thread protection for your COM object. However, when multiple processes call your DLL, You have to lock the data of the COM object to prevent data synchronization problems.
The Single or blank option indicates that our COM class can only be called in the customer's main thread. You do not need to perform synchronization for your object. The system ensures that your object is serialized when called.
BothOptionTell the system and the customer that our class is thread-safe. We can use the same Apartment (Apartment) type as the customer program, and the system will not implement thread protection for your objects, therefore, you must synchronize data in your own objects. This improves performance because the system does not synchronize the entire object.
The Free option is similar to the Both option, but requires the system to put it in a multi-threaded apartment (MTA) and put it in an object in the MTA. Its method may be called by multiple threads at the same time.
The Neutral option tells the system that our Class should be placed in the Neutral Apartment. Neutral Apartment is an Apartment that appears in COM +, so that your Class can be called by any thread, and you do not need to do synchronization, but only one Neutral Apartment can be in a process.
The Apartment and Both options are commonly used in ThreadingModel.
Support options
Connecton Points optionsTo make your COM class inherit the IConnectonPointImpl interface, and perform the following four steps: [1] In IDL (Interface Definition Language) file definition callback interface [2] Use ATL proxygenerator (proxy generator) to create proxy (proxy) class [3] to create proxy (proxy) class added to your COM object [4] For Your COM Object connection point map (connection point ing), add connection point (connection point ).
ISupportErrorInfo Option, So that your error information can be correctly transmitted along the call path. Selecting ISupportErrorInfo will make your object inherit the ISuportErrorInfoImpl interface. If you want to create an OLE Automation Object, this interface must be inherited for error handling.
IObjectWithSite (IE object support) OptionSo that your object can communicate with its container (containersite) in IE. For example, Java Script calls the COM object you wrote, your COM object can also retrieve elements on the Web page where Java Script is located.
Aggregation options
We generally choose No, that is, the inheritance between COM objects is not required. For how to use Aggregation (Aggregation), refer to the following document.
Aggregation explained
Http://www.codeproject.com/Articles/17455/Aggregation-explained
Attribute Option
If you do not select this option, you can create an ATL object in the Classic mode. If you often need to write an ATL program, you can study the ATL Attribute programming, it simplifies the development of ATL objects through some keywords, but the ATL objects with Attribute attributes cannot inherit from each other.
Add Method
In [Class View], you can see that the wizard generates three IHelloWorld for you, right-click the top IHelloWorld, [Add]-> [Add Function...] the add method window is displayed. Add the SayHello method, and add the "[in] BSTR msg" and "[out, retval] BSTR * result" parameters to the method to be added, and modify the source code (HelloWorld. cpp file), the modified format is as follows.
# Include
Usingnamespacestd;
// CHelloWorld
STDMETHODIMPCHelloWorld: SayHello (BSTRmsg, BSTR * result)
{
Wstringhead = L "received information from JavaScript => ";
Wstringcontent = head + OLE2W (msg );
* Result = W2BSTR (content. c_str ());
ReturnS_ OK;
}
The input string does not need to contain the pointer type (BSTR type), but returns the string to the caller. The variable type must be pointer type, that is, BSTR * type.
To prevent IE from popping up the warning window, we also need to add the IObjectSafetyImpl interface inheritance for our CHelloWorld class. Double-click CHelloWorld in the [Class View] window to open the HelloWorld. h file and find public IObjectWithSiteImpl. Insert code lines below
PublicIObjectSafetyImpl ,
Find "COM_INTERFACE_ENTRY (IObjectWithSite)" and insert it below
COM_INTERFACE_ENTRY (IObjectSafety)
Press [F6] Build Solution. Visual Studio automatically registers your ATL object.
Test our first ATL Object
In [Class View], double-click the IHelloWorld interface of the newly added method to open the ATLTutorial1.idl file, which is the interface definition file of the COM object. Find the COM Object Class HelloWorld in "libraryATLTutorial1Lib". The uuid value before coclass HelloWorld is the name of the HelloWorld object in the system. We need to instantiate this object through this name in HTML.
The IDL file. The ATLTutorial1Lib behind the library is the name of our ATL library. Find this library in the system's COM Object List. expand it and you will see our COM class HelloWorld, further, we can see that it inherits the IHelloWorld interface.
Right-click the solutionpolicerlistener's solutionname, which is the current solutionexceptest.htm file. The content is as follows:
<Scriptlanguage = "JavaScript" type = "text/javascript">
Function testSayHelloMethod (){
Var a = objHelloWorld. SayHello ("My name iskagula! ");
Alert ();
}
</Script>
If you want to add, delete, or modify the HelloWorld class using the Wizard, you only need to modify the ATLTutorial1.idl, HelloWorld. h, and HelloWorld. cpp files. ATLTutorial1.idl defines how your method is exposed to the outside, HelloWorld. h declares your method, and HelloWorld. cpp implements your method.
To release the DLL later, we recommend that you add the SetupProject in the current Solution to make the installation file very convenient.
Tracking Your code from HTML
In [SolutionExplorer], select the ATL Project name and press the [Alt] + [Enter] shortcut key to open the project properties page, [Configuration Properties]-> [Debugging]-> [Debugger to Launch] select [WebBrowser Debugger] and fill in your htmlocation in [http url]. If the test file test.htm is in the MyProject directory of the D partition, you can enter "file: /// D: \ MyProject \ test.htm ". Press [F5] to track the source code of your ATL object from the HTML file.
Tracking from C # project
Add a C # Win32 console project to the Solution of your ATL Project, and add a reference for [COM]-> [TypeLibraries]-> [ATLTutorial1Lib] to the project, here, ATLTutorial1Lib is the library name of our ATL library, which is immediately followed by the library keyword of the ATLTutorial1.idl file. modify Program. the cs file is as follows:
Staticvoid Main (string [] args)
{
ATLTutorial1Lib. HelloWorld hw = new ATLTutorial1Lib. HelloWorld ();
Debug. WriteLine ("==>" + hw. SayHello (" abc "));
Console. ReadKey ();
}
Open the properties page of the C # project, and select [Debug]-> [EnableDebuggers]-> [Enable native code debugging].
On the Solution Properties page, [CommonProperties]-> [Project Dependencies] Set Your C # Project to depend on your ATL Project.
Set the C # project as a startup project and press [F5] To start Debug. Then, you can Debug the code of your ATL object. If the ATL code has been modified, visual Studio will first build your ATL Project and then start your C # program.
ATL also needs to pay attention to the use of the following classes
CComPtr
CComPtr It is a smart pointer provided by ATL to reduce the Code required to write and release objects and make the code more concise. The sample code is as follows:
// Create a spDoc smart pointer
CComPtr SpDoc;
// SPDoc smart pointer to get the object
Browser-> get_Document (IDispatch **) & spDoc );
// Use the spDoc smart pointer
SpDoc-> get_Script (& pScript );
// After the code snippet ends, spDoc Automatically releases the object to which it points. You do not need to write additional code.
CComBSTR
BSTR is a string type of ATL. It is used to pass strings externally. The standard BSTR is an OLECHAR array with a length prefix and a null Terminator. The ATL class CComBSTR provides packaging for the BSTR data type. Some COM Object method calls require passing in a string object of the CComBSTR class, but our C ++ Code generally uses a string of the std: wstring type. below is the std :: conversion between wstring and CComBSTR objects.
// Convert an instance of std: wstring to a CComBSTR instance
CComBSTR bstrMember (: W2BSTR (name. c_str (); // std: wstringname
// Or use the following method to convert
BSTRbs2 = SysAllocStringLen (name. data (), name. size ());
CComBSTR bstrMember (bs2 );
// Convert a CComBSTR instance to a std: wstring instance
CComBSTRbs (L "ddd ");
Std: wstringws (bs, SysStringLen (bs ));
When the CComBSTR class is out of the range, the memory allocated by it is automatically released.
CComVariant
VARIANT is a struct object. Although it can accommodate different data types, it is mainly used to pass user objects in mixed programming with JavaScript. CComVariant is the encapsulation of VARIANT. For details, refer
Use of VARIANT and CComVariant
Http://blog.csdn.net/tangaowen/article/details/6553305
When the caller does not know the parameter type of the COM Object method, the CComVariant type parameter can be used instead.
Q How to call methods in JavaScript from ATL? Refer to the following link
ATL callback JavaScript
Http://blog.csdn.net/lee353086/article/details/8853820
Q How to return an array from an ATL object? Refer to the following link
Example of returning a string array to JavaScript from ATL
Http://blog.csdn.net/lee353086/article/details/7557333
Q how to retrieve HTML elements in ATL? Refer to the following link
Examples of enumeration of DOM elements in ATL
Http://blog.csdn.net/lee353086/article/details/9342353
Q How to publish ATL into a CAB package? Refer to the following link
Compiling simple ATL objects in PHP in VS2013
Http://blog.csdn.net/sjg20010414/article/details/20045179
References
[1] Active TemplateLibrary
Http://resources.esri.com/help/9.3/arcgisdesktop/com/COM/VCpp/ATLDiscussion.htm
[2] ATL and MFC changesand fixes in Visual Studio 2013
Http://blogs.msdn.com/ B /vcblog/archive/2013/08/20/atl-and-mfc-changes-and-fixes-in-visual-studio-2013.aspx
[3] atl com extends topcomponents
Http://msdn.microsoft.com/en-us/library/t9adwcde.aspx
[4] IE11 EnhancedProtected Mode solves the communication problem between BHO and high-permission processes
Http://blog.csdn.net/yangjian8915/article/details/11812303