简体   繁体   English

C#如何将类实例传递给c#dll方法?

[英]C# how to pass a class instance to c# dll method?

I loaded and got an instance form a dll by this code: 我通过以下代码加载并获​​得了一个dll实例:

ApiClass api = new ApiClass(this);

Assembly SampleAssembly = Assembly.LoadFrom(@"C:\plugin1.dll");
Type myType = SampleAssembly.GetTypes()[0];
MethodInfo Method = myType.GetMethod("onRun");
object myInstance = Activator.CreateInstance(myType);
try
{
    object retVal = Method.Invoke(myInstance, new object[] { api });
}

and here is the code of IApi interface: 这是IApi接口的代码:

namespace PluginEngine
{
    public interface IApi
    {
        void showMessage(string message);

        void closeApplication();

        void minimizeApplication();
    }
}

I just copied the IApi to the dll project and build it. 我刚刚将IApi复制到dll项目并构建它。 It is the code of dll: 这是dll的代码:

namespace plugin1
{
    public class Class1
    {
        public void onRun(PluginEngine.IApi apiObject)
        {
            //PluginEngine.IApi api = (IApi)apiObject;
            apiObject.showMessage("Hi there...");
        }
    }
}

but there is an error when I want to invoke the dll method: 但是当我想调用dll方法时出错:

Object of type 'PluginEngine.ApiClass' cannot be converted to type 'PluginEngine.IApi'

I just copied the IApi to the dll project 我刚刚将IApi复制到dll项目中

That's where you went wrong, you cannot copy the interface. 那是你出错的地方,你无法复制界面。 You are doing battle with the notion of type identity in .NET. 您正在与.NET中的类型标识概念进行斗争。 The identity of a type like IApi isn't just determined by its name, it also matters what assembly it came from. 像IApi这样的类型的身份不仅仅取决于它的名称,它的组合也很重要。 So you have two distinct IApi types, the one in the plugin doesn't match the one in the host. 因此,您有两种不同的IApi类型,插件中的类型与主机中的类型不匹配。

You need to create another class library project that contains the types that both the host and the plugin use. 您需要创建另一个类库项目,其中包含主机和插件使用的类型。 Like IApi. 像IApi一样。 Add a reference to this library project in both your host project and your plugin project. 在主机项目和插件项目中添加对此库项目的引用。 Now there's only one IApi. 现在只有一个 IApi。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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