Getting C# ActiveX/COM Library to Work through JScript

放肆的年华 提交于 2019-12-25 02:24:42

问题


I have checked on stackoverflow (and what seems like everywhere else). I would like to get a COM solution working so that a jscript file can be written as

var T = new ActiveXObject("MySimulator.World"); 
T.MyMethod();

It would be executed at the command prompt by

cscript mytest.js

In this case, I get the error "Automation server can't create object".

In C#, I have followed various suggestions, with the latest interface being:

[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("EAA4976A-45C3-4BC5-BC0B-E474F4C3C83B")]
public interface IComMyReaderInterface
{
    void MyFunction();
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None), Guid("0D53A3E8-E51A-49C7-944E-E72A2064F9DD"), ProgId("MySimulator.World")]
[ComDefaultInterface(typeof(IComMyReaderInterface))]
public class MyReader : IComMyReaderInterface
{
    public MyReader()
    {
         ...
    }

    public void MyFunction()
    {
         ...
    }
 ...
}

Thanks and just let me know if more information is needed.


回答1:


I'd assume the following. Your development environment is probably a 64-bit OS and your C# DLL project is probably configured to compile with Any CPU as Platform Target. Read on if that's the case.

Choose either x86 or x64 and compile the project. If you go with x86, then register your assembly with the 32-bit version of RegAsm.exe:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe /codebase assembly.dll

Then run your JavaScript test with the 32-bit version of cscript.exe:

C:\Windows\SysWOW64\cscript.exe mytest.js

If you go with x64, that would be:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe /codebase assembly.dll C:\Windows\System32\cscript.exe mytest.js

[EDITED] The following code has been verified to work using the above instructions.

C#:

using System;
using System.Runtime.InteropServices;

namespace ComLibrary
{
    [ComVisible(true)]
    [InterfaceType(ComInterfaceType.InterfaceIsDual),
        Guid("EAA4976A-45C3-4BC5-BC0B-E474F4C3C83B")]
    public interface IComMyReaderInterface
    {
        void MyFunction();
    }

    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None), 
        Guid("0D53A3E8-E51A-49C7-944E-E72A2064F9DD"), 
        ProgId("MySimulator.World")]
    [ComDefaultInterface(typeof(IComMyReaderInterface))]
    public class MyReader : IComMyReaderInterface
    {
        public MyReader()
        {
        }

        public void MyFunction()
        {
            Console.WriteLine("MyFunction called");
        }
    }
}

JavaScript (mytest.js):

var T = new ActiveXObject("MySimulator.World"); 
T.MyFunction();

Output:

MyFunction called



来源:https://stackoverflow.com/questions/20914759/getting-c-sharp-activex-com-library-to-work-through-jscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!