How do you directly call a native function exported from a DLL? Can someone just give me a small example?
Asked
Active
Viewed 510 times
3 Answers
2
This is Microsoft example:
class PlatformInvokeTest
{
[DllImport("msvcrt.dll")]
public static extern int puts(string c);
[DllImport("msvcrt.dll")]
internal static extern int _flushall();
public static void Main()
{
puts("Test");
_flushall();
}
}
If you need to generate C# DLLImport declarations from a native dll, watch this post: Generate C# DLLImport declarations from a native dll
2
Depends on what exactly you want ... I have something like this in my code but this uses the Win32 API dll's
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
then just call
GetForegroundWindow()
as if defined inside the class

scibuff
- 13,377
- 2
- 27
- 30
1
Here’s a quick example of the DllImport
attribute in action:
using System.Runtime.InteropServices;
class C
{
[DllImport("user32.dll")]
public static extern int MessageBoxA(int h, string m, string c, int type);
public static int Main()
{
return MessageBoxA(0, "Hello World!", "Caption", 0);
}
}
This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA()
is declared with the static and external modifiers, and has the DllImport
attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA.
Refer this link