Create a COM object with C #

zhaozj2021-02-16  57

Part 1: Creating a simple COM object with C #

The COM object is a ClassLibrary class that generates a DLL file. To create a simple COM object in the VS development environment, we can select "File" ->; "New Creation" ->; "Project" ->; "Visualc # Project" ->; "Class Library", then Create an engineering of Database_Comobject. It should be noted that the following conditions are required in the COM.

· Class must be the PUBLIC property. · Features, methods and events must be in the PUBLIC property. · Features and methods must be defined in class interfaces. • The event must be defined in an event interface.

A member of the PUBLIC property defined in these interfaces cannot be accessed by COM, but they can be accessed by other .NET Framework objects. To allow COM to access features and methods, we must define them in class interfaces to have a Dispid property and implement these features and methods in the class. The order in these members definitions is the order in which they are in COM. To let the COM access, you must define these events in an event interface and give them the Dispid property. The event interface should not be completed by the class, the class only the class interface (it can implement an interface, but the first interface is the default interface), and the method and characteristics, methods, methods, methods that need to make COM access should be implemented in the default interface. Features must be identified as public properties and conform to definitions in class interfaces. Events that need to be accessible are also completed in the default class interface, and they must also be identified as public properties and meet the definitions in the event interface.

Before the interface name, each interface requires a GUID feature. To generate a unique GUID, you need to run the GUIDgen.exe tool software and select "Registry Format" below is a class interface:

[Guid ( "; 694C1820-04B6-4988-928F-FD858B95C880";)] public interface DBCOM_Interface {[DispId (1)] void Init (string userid, string password); [DispId (2)] bool ExecuteSelectCommand (string selCommand) [Dispid (3)] bool next (); [Dispid (4)] void ExecutenSelectCommand (String INSCOMMAN); [Dispid (5)] String getColumndata (int POS);}

CoM event interface:

// Event interface Database_comobjectEvents [GUID ("; 47c976e0-C208-4740-AC42-41212D3C34F0";), InterfaceType (CominterFactype.InterfaceisidInd Interface DBCOM_EVENTS {}

Here is the actual class definition:

[Guid ( "; 9E5E5FB2-219D-4ee7-AB27-E4DBED8E123E";), ClassInterface (ClassInterfaceType.None), ComSourceInterfaces (typeof (DBCOM_Events))] public class DBCOM_Class: DBCOM_Interface {should be noted that, in front of the class, need Set the following features:

ClassInterface (ClassInterFaceType.none), COMSourceInterfaces (TypeOf (dbcom_events)]

ClassInterFaceType.none indicates that there is no class interface for this class. If the interface is not explicitly implemented, the class can only provide later binding access by iDISPATCH. The user hopes that the external object can access the class's function by explicitly enabling the interface, which is also the setting of the recommended ClassInterFacettribute. COMSourceInterfaces (TypeOf (dbcom_events))] Determines many interfaces provided to the external object as a COM event. In the examples of this article, we don't open any events for external objects. Below is the complete source code for COM objects:

using System; using System.Runtime.InteropServices; using System.IO; using System.Text; using System.Data.SqlClient; using System.Windows.Forms; namespace Database_COMObject {[Guid ( "; 694C1820-04B6-4988-928F- FD858B95C880 ";)] public interface DBCOM_Interface {[DispId (1)] void Init (string userid, string password); [DispId (2)] bool ExecuteSelectCommand (string selCommand); [DispId (3)] bool NextRow (); [ DispId (4)] void ExecuteNonSelectCommand (string insCommand); [DispId (5)] string GetColumnData (int pos);} // event interface Database_COMObjectEvents [Guid ( "; 47C976E0-C208-4740-AC42-41212D3C34F0";), InterfaceType (ComInterfaceType.InterfaceIsIDispatch)] public interface DBCOM_Events {} [Guid ( "; 9E5E5FB2-219D-4ee7-AB27-E4DBED8E123E";), ClassInterface (ClassInterfaceType.None), ComSourceInterfaces (typeof (DBCOM_Events))] public class DBCOM_Class: DBCOM_Interface { Private sqlconnection myconnection = null; sqldataareader myreader = null; public dbcom_class () {} public void init (String Userid, String Pas Sword) {Try {String myConnectString = "; user ID ="; userid ";; password ="; password "; Database = northwind; server = skywalker; connection timeout = 30" ;; myconnection =

new SqlConnection (myConnectString); myConnection.Open (); MessageBox.Show ( "; CONNECTED";);} catch (Exception e) {MessageBox.Show (e.Message);}} public bool ExecuteSelectCommand (string selCommand) {if (! myReader = null) myReader.Close (); SqlCommand myCommand = new SqlCommand (selCommand); myCommand.Connection = myConnection; myCommand.ExecuteNonQuery (); myReader = myCommand.ExecuteReader (); return true;} public bool NextRow () {ifReader.Read ()) {MyReader.close (); return false;} return true;} public string getColumndata (int POS) {Object obj = myreader.getValue (POS); if (Obj == null) return ";";; return obj.ToString ();} public void ExecuteNonSelectCommand (string insCommand) {SqlCommand myCommand = new SqlCommand (insCommand, myConnection); int retRows = myCommand.ExecuteNonQuery ();}}} Create a COM object before We must register this object to COM Interop. Right click on the project name in the scenario manager, click "Properties" option on the shortcut menu, and then click "Configure" ->; "Create", extend the Output section, set the value of the Register for Com Interope option to True. In this way, a COM object can interact with the manageable application. In order to make COM objects can be called by external objects, the class library combination must have a strong name. Creating a strong name requires a sn.exe name:

Sn -k Database_com_key.snk Opens AssemblyInfo.cs and modifies the contents of the following line: [Assembly: assemblykeyKeyFile ("; Database_com_key.snk";) Create an object. Creating an object generates a class library that can be imported into manageable or non-manageable code.

Part II: Create client software for accessing COM objects using Visual C

· Create a simple engineering using the VC development environment. · Import Type Library with #import Directive. • Create a Smart Pointer in the interface, perform the functions provided from the COM class from the interface. Be sure to add a Coinitialize () call when the application is loaded:

Coinitialize (NULL); Database_comobject :: DBCOM_INTERFACEPTR P (__ uuidof (Database_comobject :: dbcom_class)); db_com_ptr = p; db_com_ptr ->; init ("; scott";, "; tiger";);

The following code performs a SQL command to the CUSTOMERS database table, returns the information of the customer of the given ID:

char cmd [1024]; sprintf (cmd, "; SELECT COMPANYNAME, CONTACTNAME, CONTACTTITLE, ADDRESS FROM CUSTOMERS WHERE CUSTOMERID = '% s'";, m_id); const char * p; bool ret = db_com_ptr ->; ExecuteSelectCommand (cmd ); If (! Db_com_ptr ->; nextrow ()) return; _bstr_t mdata = db_com_ptr ->; getColumndata (3); p = mdata; m_address = (cstring) P;

转载请注明原文地址:https://www.9cbs.com/read-17623.html

New Post(0)