“The specified procedure could not be found” error

2019-02-14 15:09发布

问题:

I am developing on a 64-bit Windows 7 box with Visual Studio 2012 (11.0.51106.01 Update 1).

I have a Support project that compiles some C code into a (32-bit) DLL. In my header I have:

#define RET_TYPE(type) _declspec(dllexport) type __stdcall

RET_TYPE(int) test_dll_call(int invar);

In my C file I have:

RET_TYPE(int) test_dll_call(int invar)
{
   int retVal = 4 * invar;

   return retVal;
}

I also have a (32-bit) WPF C# application that loads the DLL inside of a class as follows:

[DllImport("MyDll.dll", CharSet = CharSet.Ansi, BestFitMapping = true, ThrowOnUnmappableChar = true)]
public static extern int test_dll_call(int invar);

This is wrapped as follows:

public void Wrap_TestDllCall()
{
   try
   {
      int outTest = 0;
      int invar = 3;

      outTest = test_dll_call(invar);
   }
   catch (Exception ex)
   {
      dllError = ex.ToString();
   }
}

When I run this in the debugger on my development box, this works fine. If I copy all the relevant files to a separate folder and run it from there, it works fine.

If I copy all the necessary folders to another computer running 32-bit Windows XP SP3 I get the following error:

System.DllNotFoundException: Unable to load DLL 'MyDll.dll': The specified procedure could not be found. (Exception from HRESULT: 0x8007007F)
   at MyNamespace.MyClass.test_dll_call(Int32 invar)
   at MyNamespace.MyClass.Wrap_TestDllCall()

I have used dependency walker on both my compiled exe and the dll; the only missing dlls it found were wer.dll and ieshims.dll, which from my research are not needed on XP.

I have installed the VS2012 C++ Redistributable, and .NET 4, and the .NET 4.0.3 update. Still no luck.

Edit As Hans points out, this appears to be that the app can't find the procedure in the DLL; I have also tried:

[DllImport("MyDll.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern int test_dll_call(int invar);

and

__declspec(dllexport) int __cdecl test_dll_call(int invar);

Which also works fine on my dev box but gives the same error on the WinXP box.

Help!

回答1:

Problem solved. Some things to note as I went through troubleshooting steps, for those who stumble upon this in the future.

  1. This error does not necessarily mean it can't find procedure X -- rather it may mean it can't find function Y, from another dll, that is called by X.
  2. Make sure to compile the DLL in 'Release' mode, as the C++ redistributable will not include the debug DLLs.
  3. Start with a shell function, and add pieces back in, one by one.

In my above test example, the problem was I was compiling as a Debug version.

However, in my complete function, that change did not fix the issue. It turns out I was missing some DLLs that dependency walker did not catch.