Since reading http://msdn.microsoft.com/zh-cn/library/ms173184 (vs.80). aspx and http://msdn.microsoft.com/zh-cn/library/system.runtime.interopservices (vs.80). aspx on C # And C ++ public language runtime can interoperate with each other to produce great interest.
The first time I used C # To Call The DLL file generated by C/C ++, I felt a little novel. In fact, it was just an "unmanaged" that runs beyond the control of the Common Language Runtime Library (CLR ).Code"(The code that runs in the control of the Common Language Runtime Library (CLR) is called" managed code "). How can it be used in managed unmanaged systems? Now let's write a simple implementation process for interested beginners (don't laugh at any problem ):
1. Use vs2008 to select other languages (C ++) to create a console applicationProgramName mydll1, select the application type as DLL, and OK
Project
Add the following declaration under the header file stdafx. h:
# Define Libexport_api extern "C" _ declspec (dllexport)
Libexport_api Int Add ( Int A, Int B );
InMydll. cppTo implement this function:
# Include"Stdafx. h"
IntAdd (IntA,IntB)
{
ReturnA+B;
}
Note that if the implementation method is declared in other header files, you must add # include "XXX. H" to reference this declared function header file.
GenerateMydll. dllAndMydll. Lib.
2. InVisual C #. netReferencesDLLFile
Create a Visual C # console application named testimportdll;
SetMydll. dllAndMydll. LibCopy to the executable file directory ():
Add reference in praogram. CSUsing system. runtime. interopservices;
DeclareMydll. dllFunction class:
Class Test
{
// [Dllimport (".. \ Lib \ cppdemo. dll")]
// Public static extern void function ();
// [Dllimport (".. \ Lib \ cppdemo. dll")]
// Public static extern int add (int I, Int J );
[Dllimport ( " .. \ Lib \ mydll1.dll " )]
Public Static Extern Int Add ( Int A, Int B );
}
Finally, the main function calls the output result of this class:
Static Void Main ( String [] ARGs)
{< P>
console. writeline ( " result: " + test. add ( 2 , 3 ). tostring ();
console. readline ();
}< span style = "color: #000000"> The following is a program. CS code:
end ():