C# importing C++ dll

20,963

Solution 1

You say:

I placed the .dll file in the program's directory...

But:

Unable to load DLL 'Libraries\lib.dll'

We need to see your DLLImport attribute creation, i.e., the C# signature of the native method. It looks to me like you probably specify the path, i.e.,

[DllImport( "Libraries\lib.dll" )];
static extern void MyNativeMethod();

Try using this instead:

[DllImport( "lib.dll" )];
static extern void MyNativeMethod();

That will search the running directory as well as through your PATH environment variable. If you specify a file path as you do I honestly don't know if it will search through PATH if the file is not found (I couldn't find mention of it in the docs).

Solution 2

There isn't enough information here to help, as you're not showing the API (in native code) you're trying to import, etc.

That being said, I'd strongly recommend reading the Platform Invoke Tutorial as well as A Closer Look at Platform Invoke on MSDN. They walk through the main issues, as well as showing many examples of how to import and use functions from a C++ DLL.

Solution 3

The best and easiest way of using a c++ dll file in c# :-

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

namespace demo1
{
    class Program
    {
        [DllImport("shi.dll", EntryPoint = "?HelloWorld@@YAXXZ")]
       public static extern int HelloWorld();
      public  static void Main(string[] args)
        {
            //Console.WriteLine(StringUtilities.HelloWorld());
            Console.WriteLine(HelloWorld());
            // public static extern void HelloWorld();
           //  HelloWorld();
            //  Console.ReadKey();
        }
    }
}
Share:
20,963
dnclem
Author by

dnclem

Updated on February 18, 2021

Comments

  • dnclem
    dnclem about 3 years

    I have a managed dll file which imports functions from a C++ dll to the managed environment. I'm using some of its functions in my program but the problem is, I get this error when I use it:

    Unable to load DLL 'Libraries\lib.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

    I placed the .dll file in the program's directory and in the system32 folder. However, it still doesn't work. I think I have to use DLLImport but I have no idea how to use it.. even after looking at some examples I am still confused. Can someone help me here?