COM and. NET Interoperability (primary)

Source: Internet
Author: User
Tags net command printf reflection visual studio
COM and. NET Interoperability (primary)
COM components are invoked from. NET in interop with. NET, and if using vs.net will become very easy, you just need to add the corresponding COM references in your project, and the compiler will quietly turn COM into a. NET assembly in the background. and calls from the traditional language invocation. NET components are less convenient. So, I sorted out the success of the personal debugging of several procedures for everyone to have some help, good nonsense less said to get to the point.



One, call. NET components from scripts such as VBScript

First we can write a. NET dll as follows

The File:netServer.cs

Using System;

Using System.Reflection;

Using System.Runtime.InteropServices;



[Assembly:assemblykeyfile ("key.snk")]

Namespace Csharpserver

{

The default is Classinterfacetype.autodispatch, which generates only the dispatch interface

Can only be used by COM clients using script, VB and other late binding methods

[ClassInterfaceAttribute (Classinterfacetype.autodual)]

public class Sharpobject

{

private string M_strname;



Public Sharpobject () {}



public string Name//property:name, Get/set

{

get {return m_strname;}

set {m_strname = value;}

}

}

}



The second File:test.vbs

Dim obj

Set obj = CreateObject ("Csharpserver.sharpobject")

Obj. Name = "Chang Ming"

MsgBox "My Name is" & obj. Name



The two files are compiled as follows, for clarity we use command-line tools (command-line tool environments can start-->microsoft Visual studio. net-->visual Studio. NET Tools-->visual In Studio. NET command Prompt)

1, the key file is generated to sign the assembly strong name

Sn-k key.snk



2, using Strong name signature, compiled into class library,

Csc/t:library Netserver.cs



3, Build type library

TlbExp netserver.dll/out:netserver.tlb



4, Register DLL

RegAsm Netserver.dll



5, moving into the GAC global Assembly cache

Gacutil-i Netserver.dll



6, call the test script

WScript Test.vbs



Here are a few points to note, 1, and you must sign the assembly so that it has a strong name. 2, the assembly must be registered with RegAsm, and it will add the appropriate entry in the registry. 3, you must move the signed strong-named assembly into the global assembly cache (GAC). 4, you must first install ScriptEngine, Microsoft's script execution engine. This is the call from the script. NET assembly, oh, very simple? J



Two, call from C + + +. NET components

Or a program, oh, the program is My life:

File1 Name:netServer.cs

Using System;

Using System.Reflection;

Using System.Runtime.InteropServices;



[Assembly:assemblykeyfile ("key.snk")]

Namespace Csharpserver

{



public interface Iobject//declaration interface

{

Double Sub (double c,double d);

}



[ClassInterfaceAttribute (Classinterfacetype.autodual)]



public class Sharpobject:iobject

{

private string M_strname;



Public Sharpobject () {}



public string Name//property:name, Get/set

{

get {return m_strname;}

set {m_strname = value;}

}



Public double Add (double a,double b)

{

Console.WriteLine ("The answer is {0}", a+b);

return a+b;

}

Public double Sub (double c,double d)//Implement Interface method

{

Console.WriteLine ("The answer is {0}", c-d);

return c-d;

}

}

}





File2 Name:comclient.cpp

#include <windows.h>

#include <stdio.h>

#include <iostream.h>

#pragma warning (disable:4278)



#import "Netserver.tlb" No_namespace named_guids



int main (int argc, char* argv[])

{

Iobject *cpi = NULL;

int retval = 1;



Initialize COM and create an instance of the Interfaceimplementation class:

CoInitialize (NULL);

HRESULT hr = CoCreateInstance (Clsid_sharpobject,

Null

Clsctx_inproc_server,

Iid_iobject,

Reinterpret_cast<void**> (&AMP;CPI));



if (FAILED (HR))

{

printf ("couldn ' t create the instance!... 0x%x\n ", HR);

}

Else

{



printf ("Calling function.\n");



retval = 0;

cout<< "10-4=" <<cpi->sub (10,4) <<endl;

printf ("returned from function.\n");



Cpi->release ()//Free COM object

}



Be a good citizen and clean up COM:

CoUninitialize ();

return retval;

}



Compilation method or as before

1, the key file is generated to sign the assembly strong name

Sn-k key.snk



2, using Strong name signature, compiled into class library,

Csc/t:library Netserver.cs



3, Build type library//This step is important

TlbExp netserver.dll/out:netserver.tlb



4, Register DLL

RegAsm Netserver.dll



5, moving into the GAC global Assembly cache

Gacutil-i Netserver.dll



6, compile the test program

CL COMClient.cpp

7, Executive Comclient.exe



Description

Calling COM in C + + is troublesome by invoking the COM library function CoInitialize (NULL), initializing it, and then calling HRESULT hr = CoCreateInstance (Clsid_sharpobject,

Null

Clsctx_inproc_server,

Iid_iobject,

Reinterpret_cast<void**> (&AMP;CPI));

Where Clsid_sharpobject is the class ID of the Sharpobject class (COM Class) it is generated by the tool to uniquely identify the Sharpobject class, iid_iobject uniquely identify the Iobject interface, If CoCreateInstance successfully created a COM object, then failed (HR) will be false, and after you get a pointer to a COM object, you can use it to invoke the method in the COM object.



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.