简体   繁体   中英

DllImport fails on windows XP SP3 but works on windows 7

I created a sample application from this site http://www.codeproject.com/Articles/9826/How-to-create-a-DLL-library-in-C-and-then-use-it-w It creates a C code and consumes in C# application.

 #include <stdio.h>

 extern "C"
 {
  __declspec(dllexport) void DisplayHelloFromDLL()
   {
   printf("Hello from DLL !\n");
   }
 }

The C# code:

using System;
using System.Runtime.InteropServices;     // DLL support

class HelloWorld
{
  [DllImport("TestLib.dll")]
  public static extern void DisplayHelloFromDLL ();

  static void Main ()
  {
    Console.WriteLine ("This is C# program");
    DisplayHelloFromDLL ();
  }
}

This works well on Windows 7. I have built the code on Visual studio 2010 on windows 7 machine. When i try to run the exe on windows XP it fails with following exception being thrown:Unable to load DLL 'TestLib.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

The most likely explanation, with probability close to 1 is that the Windows 7 machine has the MSVC runtime installed, but the XP machine does not.

Download the redistributable for the VS2010 MSVC runtime and install it on the XP machine. Your code should then work. The runtime is already on the Windows 7 machine because that is your development machine.

FWIW, your p/invoke is not quite correct. It fails to specify the calling convention. It should be:

[DllImport("TestLib.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern void DisplayHelloFromDLL();

Compile a simple hello world executable console application on Windows 7, and try to run that alone on Windows XP. It should be more verbose than a DLL. It will either complain that it's lacking some DLL's or there's a 32/64 bit mismatch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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