Use C # To create a COM Object

Source: Internet
Author: User
Turn: http://www.bc-cn.net/Article/kfyy/vc/jszl/200708/6020.html

In this articleArticle, We will discuss the following issues:

· Use C # To create a simple COM Object (using the InterOP feature of COM ).

· Access com from the VC ++ client. The client software uses the typelibrary (. TLB file ). To make it simple and convenient for developers to use and test, we use the northwind database in the default installation of SQL Server database software.

· Modify the sqlserver name in the COM Object and connect to sqlserver.

· We have created the usernames and passwords used to connect to the database for Scott and tiger respectively. We can use them or other existing usernames and passwords.

Part 1: use C # To create a simple COM Object

The COM object is a classlibrary class that generates DLL files. To create a simple COM object in the vs development environment, select "file"> "new"> "project"> "VisualC # project"> "class library", and create a project named database_comobject.
Note that calling the VC # object in COM requires the following conditions:
· The class must be public.
· Features, methods, and events must be public.
· Features and methods must be defined in class interfaces.
· Events must be defined in the event interface.

Not the public class members defined in these interfaces cannot be accessed by COM, but they can be accessed by other. NET Framework objects. To enable com to access features and methods, we must define them in the class interface so that they have the dispid attribute and implement these features and methods in the class. The order in which these members are defined is the order in COM. To enable events in the com domains class, you must define these events in the event interface and assign them the dispid attribute. The event interface should not be completed by the class, and the class only implements the class interface (it can implement more than one interface, but the first interface is the default Interface ), methods and features that need to be accessed by COM should be implemented in the default Interface. Methods and features must be identified as public and comply with the definition in the class interface. Events that need to be accessed by com are also completed in the default class interface. They must also be identified as public and comply with the definitions in the event interface.

Each interface requires a guid before the interface name. To generate a unique guid, run the guidgen.exe tool and select "Registry format ".

The following 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 nextrow ();
[Dispid (4)]
Void executenonselectcommand (string inscommand );
[Dispid (5)]
String getcolumndata (int pos );
}

Com event interface:
// Event interface database_comobjectevents
[GUID ("47c976e0-c208-4740-ac42-41212d3c34f0"), interfacetype (cominterfacetype. interfaceisidispatch)]
Public interface dbcom_events
{
}

The actual class definition is as follows:

[GUID ("9e5e5fb2-219d-4ee7-ab27-e4dbed8e123e "),
Classinterface (classinterfacetype. None ),
Comsourceinterfaces (typeof (dbcom_events)]
Public class dbcom_class: dbcom_interface
{
Note that you must set the following features before the class:
Classinterface (classinterfacetype. None ),
Comsourceinterfaces (typeof (dbcom_events)]

Classinterfacetype. None indicates that no class interface is generated for this class. If the interface is not explicitly implemented, the class can only be bound to access through idispatch. You want to explicitly enable external objects to implement the functions of the class through the interface implemented by the class. This is also the recommended classinterfaceattribute setting.

Comsourceinterfaces (typeof (dbcom_events)] identifies many interfaces provided to external objects as com events. In this example, we do not open any events to external objects.

Below is the complete COM ObjectSource code:
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-4121212d3c34f0 "),
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;
Sqldatareader myreader = NULL;

Public dbcom_class ()
{
}

Public void Init (string userid, string password)
{
Try
{
String myconnectstring = "User ID =" + userid + "; Password =" + password +
"; Database = northwind; server = Skywalker; Connect 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 ()
{
If (! Myreader. 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 donews = mycommand. executenonquery ();
}
}
}
Before creating a COM object, we must register the object with COM InterOP. Right-click the project name in solution manager, click "properties" in the shortcut menu, and then click "configuration"-> "CREATE" to expand the output section, set the value of the Register for com InterOP option to true. In this way, a COM object can be used with manageability applications.Program.

To enable the COM object to be called by an external object, the class library combination must have a strong name. The Sn. EXE name is required to create a strong name:
Sn-K database_com_key.snk
Open assemblyinfo. CS and modify the following line: [Assembly: assemblykeyfile ("database_com_key.snk")]
Create an object. Creating an object will generate a file that can be imported to manageability or non-manageability.CodeClass Library.

Part 2: Use Visual C ++ to create client software for accessing COM objects
· Create a simple project using the VC ++ development environment.
· Use # import ctictive to import the Type Library.
· Create a smart pointer in the interface to execute the functions provided by the COM class from the interface. Make sure that the coinitialize () call is added 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 runs an SQL command on the customers database table to return the information of the customer with 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;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.