How C # calls a function in an unmanaged dynamic library, such as a dynamic library written with VC6, the process of C # calling a dynamic library is much faster than a Java call DLL dynamic Library, as illustrated in the following example.
1. Create an unmanaged dynamic library
The code is as follows:
//这一句是声明动态库输出一个可供外不调用的函数原型.
extern "C" __declspec(dllexport) int add( int , int );
int add( int a, int b)
{
//实现这个函数returna+b;
}
Note that the above code, must add extern "C", can not be generated in the dynamic library of the exported function name is not add, but like? add@ @YAHHH @z appearance, followed by the function name add to locate functions of the portal will be problematic.
Save as a C or CPP file, and then use command cl (This command VC6 provides) to compile a dynamic library, which commands the following:
C:>cl /LD MyLib.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8804 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.
MyLib.cpp
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
You can see in the C-packing directory generated you want the dynamic library MyLib.Dll, but also accompanied by the generation of MyLib.lib, Mylib.obj, mylib.exp files, the above command CL parameter/LD is to generate dynamic library files
2. Write C # program call Dynamic Library
using System;
using System.Runtime.InteropServices; //这是用到DllImport时候要引入的包
public class InvokeDll{
[DllImport( "MyLib.dll" , CharSet=CharSet.Auto)]
staticexternint add( int a, int b); //声明外部的标准动态库, 跟Win32API是一样.
public static void Main()
{
Console.WriteLine(add(10,30));
}
}