简体   繁体   中英

How to create an C#.Net DLL to use in JavaScript

I have created a .Net DLL with few simple classes. I have registered the DLL using RegAsm and I got a message that types were registered successfully.

RegAsm Syntax Used :

C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319>RegAsm.exe "D:\\Projects\\TestDLL.Core.dll"

C# Code:

namespace MyTestDLL.Core    
    {  
        public class PacketInfo    
        {    
          // constructor
          public PacketInfo()
          {
          }

          public string HostName { get; set; }
            //   and so on ......

        }    
    }

I have set the ComVisible property to true in AssemblyInfo.cs file of this DLL. // [assembly: ComVisible(true)]

However when I create an object out of it in JavaScript and run the script in Command prompt , I'm getting either it is not an object or null.

JS Code :

  var testObj = new ActiveXObject(MyTestDLL.Core.PacketInfo); testObj.HostName = "Test"; 

Can anyone advise me how to resolve this ?

You need to add a ProgId attribute to the class, something like this:

[Guid("some guid that you will never change")]
[ProgId("MyLib.PacketInfo")] // this is arbitrary
public class PacketInfo    
{
    ....
}

The guid is optional, but if you don't set it yourself, it will be something you won't control, so it's better to define it. And of course I did not add the ComVisible because you already defined it at assembly level (I personnally prefer to set it at class level).

Then, once registered, you shall be able to use it like this (use the progid as a string):

var testObj = new ActiveXObject('MyLib.PacketInfo');
testObj.HostName = "Test";

I was able to achieve that by adding the following line to My DLL just above the class,

 [Guid("A32AB771-9967-4604-B193-57FAA25557D4"), ClassInterface(ClassInterfaceType.None)] 

Earlier I wasn't having the ClassInterfaceType part in my code. Also ensure that each of your classes are having unique GUID. FYI : You can create GUID using Visual Studio Tools GUID Creator GUI.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM