如何使用C#加载DLL?

时间:2013-08-26 15:57:09

标签: c# dll pinvoke

我有一个小DLL,它有3个功能:Init,Load和run。 我是c#的新手,所以当我在这里阅读问题时,我已经打开了一个控制台项目并希望加载DLL并使用它的功能。 不幸的是 - 它没有用。任何人都可以建议出了什么问题?

这是我得到的错误:

Unable to find an entry point named 'Init' in DLL 
'....path to my DLL....'.

这是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
   class Program
    {

       [DllImport("C:\\Desktop\\DLLTest.dll", CharSet = CharSet.Unicode)]
        public static extern bool Init();

        [DllImport("C:\\Desktop\\DLLTest.dll", CharSet = CharSet.Unicode)]
         public static extern bool Load(string file);


         [DllImport("C:\\Desktop\\DLLTest.dll", CharSet = CharSet.Unicode)]
        public static extern bool Play();



        static void Main()
        {
            Console.WriteLine("got till here!!!");

            Init();

            Load("C:\\Desktop\\the_thing_about_dogs_480x270.mp4");
            Play();

        }
    }

}

我唯一可以怀疑的可能是我不是在创建一个实例? 除此之外,没有线索:(

*编辑:* 这是DLL:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DLLTest
{
    public class DLLTestApi
    {
    myInfo localPlay;

    public bool Init()
    {
        localPlay =  new myInfo();

        return true;

    }


    public bool Load(string file)
    {
        localPlay.Load(file);
        return true;
    }
    public bool Play()
    {
        localPlay.StartNewThread();
        return true;
    }

    public bool Stop()
    {
        localPlay.DxStopWMp();
        return true;

    }
    public bool Pause()
    {
        localPlay.DxPause();
        return true;
    }

    public bool Resume()
    {
        localPlay.DxResume();
        return true;
    }
    public bool Close()
    {
        localPlay.DxClose();
        return true;
    }
}
}

2 个答案:

答案 0 :(得分:2)

错误消息清楚地告诉您问题所在。您的DLL不会导出名为Init的函数。可能的原因包括:

  1. DLL不是非托管DLL。
  2. DLL根本不会导出该名称的函数。
  3. DLL导出该函数,但名称已修饰或损坏。
  4. 诊断错误的最简单方法可能是使用Dependency Walker之类的工具来检查DLL的导出。

    <强>更新

    从编辑到问题,很明显第1项是原因。您的DLL是托管DLL,尝试使用p / invoke访问它是不正确的。只需将其添加为控制台应用程序项目的参考。

答案 1 :(得分:0)

要动态加载dll,不确定它是否适用于托管dll,请使用System.Reflection中的Assembly.LoadFrom();

要创建实例,请使用System.Activator中的Activator.CreateInstance();