- Prepare the C++ code:
1 create the solution 'TestConsole' by VS.
2 In this solution, add a new project CppDeno with mode 'Win32 Console Application' and application type 'DLL'
3 In file CppDemo.cpp add the code as below:
extern "C" __declspec(dllexport) int Add(int a,int b) {
return a + b;
}
4 compile this simple project.
- Static call the C++ dll:
1 Under solution 'TestConsole', add new project 'TestDemo'
2 In program.cs file, add below code to Main method:
Console.WriteLine(Add(1, 2));
Console.Read();
3 Copy the CppDemo.lib & CppDemo.dll to debug folder of this project
4 Press key 'F5' to run
- Dynamic call C++ code:
1 Create new class NativeMethod.cs, the code as below:
using System;
using System.Runtime.InteropServices;
namespace TestDemo
{
internal class NativeMethod
{
[DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
public static extern int LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);
[DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
public static extern IntPtr GetProcAddress(int hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName);
[DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
public static extern bool FreeLibrary(int hModule);
}
}
2 add delegate definition to Program.cs:
delegate int Add(int a, int b);
3 update method Main as below:
static void Main(string[] args) {
//1. 动态加载C++ Dll
int hModule = NativeMethod.LoadLibrary(@"c:CppDemo.dll");
if (hModule == 0) return;
//2. 读取函数指针
IntPtr intPtr = NativeMethod.GetProcAddress(hModule, "Add");
//3. 将函数指针封装成委托
Add addFunction = (Add)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(Add));
//4. 测试
Console.WriteLine(addFunction(1, 2));
Console.Read();
}
No comments:
Post a Comment