【问题标题】:COM object work in Console application but not in DLLCOM 对象在控制台应用程序中工作,但不在 DLL 中
【发布时间】:2016-05-18 19:56:18
【问题描述】:

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

我正在尝试创建一个 DLL,它应该只包含一个函数,其他程序员可以在他们的项目中引用该函数以使用该函数。该函数只是获取一个已经在运行的对象并将其返回给调用者。这是一个获取正在运行的 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(); 表示该类没有注册。

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

我在这里缺少什么?

【问题讨论】:

  • 您的 EXE 项目的项目 > 属性 > 构建选项卡 > 目标平台设置很重要。

标签: c# dll com sap


【解决方案1】:

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

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

【讨论】:

  • 1 号做到了。我试图在 64 上构建 DLL 和可执行文件,但无济于事。但是当我强迫两者都建立在 X86 上时,它就可以工作了。我确实在方法中包含了数字 2,但它对 64 位没有任何作用,也许它对 32 位构建也有帮助。谢谢! =)
猜你喜欢
  • 1970-01-01
  • 2021-11-27
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-23
相关资源
最近更新 更多