Hello World through PInvoke

I am trying to do something in C # requiring a call to some unmanaged DLLs, a process that I know nothing about! I found the โ€œHello Worldโ€ tutorial , which should be as simple as copying and pasting a couple of lines of code from below:

using System; using System.Runtime.InteropServices; namespace PInvokeTest { class Program { [DllImport("msvcrt40.dll")] public static extern int printf(string format, __arglist); public static void Main() { printf("Hello %s!\n", __arglist("World")); Console.ReadKey(); } } } 

This compiles and runs to completion without any errors, however nothing is printed by the time it gets into ReadKey() .

Did I miss an important setup step? The project is built for .NET 4.6.1 (in case it matters for the version of the DLL or something else).

+6
source share
1 answer

Maybe version msvcrt* , which you use is a problem. If I create a console application with your immutable code, I get the same result - without output.

If I changed the reference dll from msvcrt40.dll to msvcr120.dll , then I will see the expected result.

 [DllImport("msvcr120.dll")] public static extern int printf(string format, __arglist); public static void Main() { printf("Hello %s!\n", __arglist("World")); Console.ReadKey(); } 

Additional Information

Various numbered versions of msvcrt* track versions of Visual Studio:

  • MSVCRT70.DLL Visual Studio.NET.
  • MSVCRT71.DLL Visual Studio 2003
  • MSVCRT80.DLL Visual Studio 2005
  • MSVCRT90.DLL Visual Studio 2008
  • MSVCRT100.DLL Visual Studio 2010
  • MSVCRT110.DLL Visual Studio 2012
  • MSVCRT120.DLL Visual Studio 2013

This version numbering option has changed in VS2015 due to the confusion and fragile chains of dependencies created. More information about these changes can be found here:

Great CRT Refactoring

Introduction of a universal CRT

+8
source

All Articles