First, create a C language source file test.c
void Swap (int* A, int* b)
{
int c = *a;
*a = *b;
*b = C;
}
Then download mingw64, unzip, go into the bin directory, see if there are gcc.exe, as long as the download is correct there are certain, you can add this bin directory to environment variables, you can run GCC anywhere. The lazy way is to directly copy the test.c just done to this bin directory, and Gcc.exe in a directory, and then in this directory, hold down the SHIFT key is not loose, and then click the right mouse button in the margin, you can see in the right button menu "Run this directory command prompt" option, open, Enter command
gcc -shared -o test.dll test.c
You can compile the C source file into a DLL, the name is Test.dll (directly with Cygwin inside GCC is not, if you do not know what Cygwin is, ignore this sentence. Choose to sort by modified time to see the generated test.dll at the top of this directory
Then build the C # console project in VS, compile it and build it successfully to generate the desired directory. Then right-click on the item, choose to open it in Explorer, and then copy the Test.dll to the debug directory under Bin, and then follow the code below.
Using System;
Using System.Runtime.InteropServices;
Internal class program
{
[DllImport (' test.dll ', CharSet = CharSet.Unicode)] public
unsafe static extern void Swap (int* A, int* b);
private static void Main (string[] args
{
int a = 1;
int b = 2;
Console.WriteLine ($ "Before Swap a={a},b={ b} ");
Unsafe
{
swap (&a, &b);
}
Console.WriteLine ($ "After Swap a={a},b={b}");
Console.WriteLine ("\ n");
Console.readkey ();
}
The DLL import attribute declares the function to call, and this method can then be invoked. Because you use pointers and address symbols in C # source code, you use a unsafe code block.
Note: You do not need to refer to the DLL in the project reference, just put it together with the executable file.
Note: Because the unsafe code block is used, the compilation cannot pass, and it is OK to allow the unsafe hook on the Build tab inside the project properties.
Attention:using System.Runtime.InteropServices;