Here we are talking about the issue of C # Calling standard dynamic libraries. I have mentioned in my previous files that C # uses the same principle to call Win32API. here I will explain in detail how to use C to write a standard dynamic library and then let C # Call it. (This article is suitable for beginners. There is no redundant code in the middle. It is concise and clear)
Software environment: VC6.0 (of course other versions of VC5 can also be used)
1. Create a standard dynamic library
_ Declspec (dllexport) int _ cdecl add (int, int); // This statement declares that the dynamic library outputs a prototype of a function that is available for external calls.
Int add (int a, int B) {// implement this function
Return a + B;
}
The preceding three lines of code declare an add method. The input parameter is the sum of the two int parameters and is saved as MyLib. c.
Then execute the compilation command.
H: XSchoolC #-SchoolHowTo> cl/LD MyLib. c
Microsoft (R) 32-bit C/C ++ Optimizing Compiler Version 12.00.8168 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.
MyLib. c
Microsoft (R) Incremental Linker Version 6.00.8447
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.
/Out: MyLib. dll
/Dll
/Implib: MyLib. lib
MyLib. obj
Creating library MyLib. lib and object MyLib. exp
If the above output is confirmed, the dynamic library is successfully generated.
2. Write a C-Sharp program to call the dynamic library
Using System;
Using System. Runtime. InteropServices; // This is the package to be introduced when you use DllImport.
Public class InvokeDll {
[DllImport ("MyLib. dll", CharSet = CharSet. Auto)]
Static extern int add (int a, int B); // declare an external standard dynamic library, which is the same as Win32API.
Public static void Main (){
Console. WriteLine (add (10, 30 ));
}
}
Save as the InvokeDll. cs file, and put it in the same directory as MyLib. dll to compile the file.
H: XSchoolC #-SchoolHowTo> csc invokedll. cs
Invokedll.exe will be generated to execute this file.
The above is the entire process of calling the standard dynamic library for C-Sharp.