来源与前一阵子有一个朋友请教我关于c#调用c/cpp dll 的方式
1. cpp/c 封装成dll
环境:vs2019 项目类型:新建空项目 文件类型:c/cpp fileContent:
1 2 3 4 5 6 7 8 9 10 11 12
using namespace std ;extern "C" { void __declspec(dllexport) myPrint(){ cout << "hello world" << endl ; } int __declspec(dllexport) a(int b) { return b; } }
项目属性:dll
2. c# 调用端
环境:vs2019 项目类型:新建空项目 文件类型:c#控制台程序 fileContent:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
using System;using System.Collections.Generic;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Threading.Tasks;namespace hellocaller{ class { [DllImport("kernel32.dll" , EntryPoint = "LoadLibrary" )] static extern int LoadLibrary ( [MarshalAs(UnmanagedType.LPStr)] string lpLibFileName) ; [DllImport("kernel32.dll" , EntryPoint = "GetProcAddress" )] static extern IntPtr GetProcAddress (int hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName) ; [DllImport("kernel32.dll" , EntryPoint = "FreeLibrary" )] static extern bool FreeLibrary (int hModule) ; delegate int A (int b) ; static void Main (string [] args) { int hModule = LoadLibrary(@"..\hello\Release\hello.dll" ); IntPtr intPtr = GetProcAddress(hModule, "a" ); A a = (A)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(A)); Console.WriteLine(a(3 )); FreeLibrary(hModule); } } }
近期评论