实战托管COM调用非托管的类库全过程

平台:

      VS2005

      C#2.0

     .net framework 2.0

      VBScript

 

用途:

再做WMI或者VBScript编程时不能直接调用其它类,为了代码复用, 把第三方类库封装在COM组件, 以致于VBScript能调用第三方类库的功能. 本例适用于基于windows的WMI编程开发. 作为VBScript在ASP中的调用第三方类,可以把COM做成ActiveX控件.此功能简单,所以只是创建C#中的COM Interop模式,而没采用COM+的服务器组件模式.

 

功能:

通过第三方的一个类,提取密码, 并在VBScript中实现

 

步骤一:

创建在VS2005中建一个新项目,选择Class Library,命名: PwMatrixInterop. 在类中添加using System.Runtime.InteropServices

 注意: .NET中StringBuild能够作为IN/OUT参数传递,而String不能.

 

C#代码

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;

namespace PwMatrixInterop
{
    public interface IPwMatrix
    {
        string ServerName
        {
            set;
        }
        string UserId
        {
            set;
        }
        string GetPassword();
    }


    // ***
    // *** This is the class which wraps the Dll, it can be any name you choose.
    // ***
    internal class PwCrypt
    {

        // ***
        // *** DllImport is similar to a declaration in VB.
        // ***
        [DllImport("PwCrypt.Dll")]

        // ***
        // *** The second line cues the compiler tor the DLL entry point
        // *** Since PwGet is expecting a LPStr type we added the MarshalAs to be safe
        // ***
        public static extern int pwGet(string serverName, string userId,[MarshalAs(UnmanagedType.LPStr)] System.Text.StringBuilder sb);
    }

    [ClassInterface(ClassInterfaceType.AutoDispatch)]
    [ComVisible(true)]
    public class PwMatrixEntry : IPwMatrix
    {
        private string strServerName;
        private string strUserId;

        public string ServerName
        {
            set
            {
                this.strServerName = value;
            }
        }
        public string UserId
        {
            set
            {
                this.strUserId = value;
            }
        }
        // ***
        // *** this sesction shows how to call the above class
        // *** the length of 151 allows for the largest entry within pwGet
        // ***
        public string GetPassword()
        {
            if(this.strServerName.Trim() == "")
            {
                Console.WriteLine("PwMatrix did not get the ServerName.");
                return "";
            }
            if (this.strUserId.Trim() == "")
            {
                Console.WriteLine("PwMatrix did not get the UserId.");
                return "";
            }
            System.Text.StringBuilder sbPw = new System.Text.StringBuilder(151);
            try
            {
                Console.WriteLine("Start to get password from PwMatrix.");
                int iRet = PwCrypt.pwGet(this.strServerName,this.strUserId, sbPw);
                if (iRet == 1)
                {
                    Console.WriteLine("Got the password from PwMatrix successfully.");
                }
                else
                {
                    Console.WriteLine("Failed to extract the password from PwMatrix.");
                    return iRet.ToString();
                }
            }
            catch(COMException ex)
            {
                Console.WriteLine("PwMatrix Exception Source: " + ex.Source);
                Console.WriteLine("PwMatrix Exception Message: " + ex.Message);
            }
            return (sbPw.ToString().Trim());
        }
    }
}

 

步骤二:

创建强命名

打开命令行窗口, 输入:

cd C:/Program Files/Microsoft Visual Studio 8/SDK/v2.0/Bin

sn -k PwMatrixAssemblyKey.snk

 

步骤三:

引用PwMatrixAssemblyKey.snk key进入VS2005. 在VS2005中打开

Project--> PwMatrixInterop Properties 面板. 选择Signing, 打上Sign the assembly选项, 选择强命名Key PwMatrixAssemblyKey.snk

 

PS:如果添加到AssemblyInfo.cs中,VS2005会报警告信息. 可以用如下方式禁止报警告错误

//#pragma warning disable 1699
//[assembly: AssemblyKeyFile(@"C:/workspace/PwMatrixInterop/PwMatrixAssemblyKey.snk")]
//#pragma warning restore 1699

 

步骤四:

编译得到COM PwMatrixInterop.DLL

Build PwMatrixInterop

 

步骤五:

注册COM PwMatrixInterop

在命令行窗口输入:

cd C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727

RegAsm.exe PwMatrixInterop.DLL /codebase

注意: 使用 Regasm.exe 注册程序集之后,可以将该程序集安装在全局程序集缓存中,以便可以从任何 COM 客户端激活它。如果程序集仅准备由单个应用程序激活,则可以将它放到该应用程序的目录中。.NET framework2.0下不带 Gacutil.exe 可以从VS2005的安装目录下的,SDK/V2中找到. Copy gacutil.exe和gacutil.exe.config可以在当前目录下运行.

 

步骤六:

在VBScript中调用PwMatrixInterop类

Test.vbs

 

VBScript代码

On Error Resume Next
dim objPW
dim strReturn,intReturn

Set objPW = CreateObject("PwMatrixInterop.PwMatrixEntry")
Call ErrorHandler
objPW.ServerName="HZHWD086"
objPW.UserId="IWAM_HZHWD086"
strReturn = objPW.GetPassword()
Call ErrorHandler
WScript.Echo "The Password is :" & strReturn


Sub ErrorHandler()
Dim strError
If Err Then
strError = VbCrLf & "Number (dec) : " & Err.Number & _
                VbCrLf & "Number (hex) : &H" & Hex(Err.Number) & _
                VbCrLf & "Description  : " & Err.Description & _
                VbCrLf & "Source       : " & Err.Source
               
WScript.Echo strError
End If
End Sub

 

步骤七:

Test Successfully!

 

 

 

Reference:

注册

http://msdn.microsoft.com/zh-cn/library/tzat5yw6(VS.80).aspx

http://msdn.microsoft.com/zh-cn/library/yf1d93sz(VS.80).aspx

 

CLR 完全介绍

http://msdn.microsoft.com/zh-cn/magazine/cc164193.aspx#S8

http://msdn.microsoft.com/en-us/magazine/cc164193.aspx 

 

工具:P/Invoke Interop Assistant

http://www.codeplex.com/clrinterop/SourceControl/ListDownloadableCommits.aspx

http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值