COM 对象在控制台应用程序中工作但不在 DLL 中

COM object work in Console application but not in DLL

我找不到与此相关的问题,或者我太笨了,无法理解可以应用其他解决方案。开始了。

我正在尝试创建一个 DLL,它应该只包含一个函数,其他程序员可以在他们的项目中引用该函数以使用该函数。该函数只是获取一个已经 运行 和 return 的对象给调用者。这是一个获取 运行 和 return SAP 对象的函数。

下面的DLL代码

using System;
using SAPFEWSELib;
using SapROTWr;

namespace SAPCon
{
    public class SAPObj
    {
            public static GuiSession CreateNewSession()
        {
            SapROTWr.CSapROTWrapper sapROTWrapper = new SapROTWr.CSapROTWrapper();
            object SapGuilRot = sapROTWrapper.GetROTEntry("SAPGUI");
            object engine = SapGuilRot.GetType().InvokeMember("GetSCriptingEngine", System.Reflection.BindingFlags.InvokeMethod, null, SapGuilRot, null);
            GuiApplication sapGuiApp = engine as GuiApplication;
            GuiConnection connection = sapGuiApp.Connections.ElementAt(0) as GuiConnection;
            GuiSession session = connection.Children.ElementAt(0) as GuiSession;
            int c = (connection.Children as GuiComponentCollection).Count;
            session.CreateSession();

            int err = new int();
            int ses = new int();
            do
            {
                try
                {
                    session = connection.Children.ElementAt(c) as GuiSession;
                    ses = session.Info.SessionNumber;
                    err = 0;
                }
                catch (Exception e)
                {
                    err = e.HResult;
                }
            } while (err == 614);

            return session;
            }
    }
}

这是试图测试 dll 的程序的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SAPFEWSELib;
using SapROTWr;
using SAPCon;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            GuiSession g;
            g = SAPCon.SAPObj.CreateNewSession();

            int s;
            s = g.Info.SessionNumber;
            Console.WriteLine(s);
            Console.ReadKey();
        }
    }
}

如果我将整个 DLL 代码放在常规控制台应用程序中,它可以完美运行,但是当我引用 dll 并尝试使用该函数时,我在第一行出现异常 SapROTWr.CSapROTWrapper sapROTWrapper = new SapROTWr.CSapROTWrapper(); 表示 class 未注册。

我认为这是我的 DLL 有问题,而不是 SAP Dll,因为它们在 运行 来自应用程序时工作正常。我在我的 dll 上做了一个 regasm 32bit,它没问题,我尝试了一个 regsvr,但它找不到入口点。

我在这里错过了什么?

在这种情况下您可能需要检查的几件事是:

  1. 检查正确的架构。在 "runnable" 类型的项目 "Prefer 32-bit" 中导致选项存在非常大的问题所以你可能认为你是 运行 AnyCPU 但实际上你强制 x86 架构
  2. 检查应用 [STAThreadAttribute] 到有问题的方法是否解决了问题
  3. 尝试将两个项目构建到同一目录 - 如果它解决了问题,则意味着您在引用项目中缺少一些依赖项的文件