若是你常翻看FCL的源码,你会发现这里面有很多方法借助了C/C++的力量让C#更快更强悍,以下所示:python
[DllImport("QCall", CharSet = CharSet.Unicode)] [SecurityCritical] [SuppressUnmanagedCodeSecurity] private static extern bool InternalUseRandomizedHashing(); [DllImport("mscoree.dll", EntryPoint = "ND_RU1")] [SuppressUnmanagedCodeSecurity] [SecurityCritical] public static extern byte ReadByte([In] [MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs);
联想到上一篇阿里短信netsdk也是全用C++实现,而后用C#作一层壳,二者相互打辅助彰显更强大的威力,还有不少作物联网的朋友对这种.Net互操做技术太熟悉不过了,不少硬件,视频设备驱动都是用C/C++实现,而后用winform/WPF去作管理界面,C++仍是在大学里学过,好多年没接触了,为了练手这一篇用P/Invoke来将二者相互打通。ios
这里我用vs2019建立C++的Console App,修改两个配置: 将程序导出为dll,修改为compile方式为Compile as C++ Code (/TP)
。dom
简单类型是最好处理的,基本上int,long,double都是一一对应的,这里我用C++实现了简单的Sum操做,画一个简图就是下面这样:异步
新建一个cpp文件和一个h头文件,以下代码。函数
--- Person.cpp extern "C" { _declspec(dllexport) int Sum(int a, int b); } --- Person.h #include "Person.h" #include "iostream" using namespace std; int Sum(int a, int b) { return a + b; }
有一个注意的地方就是 extern "C"
,必定要用C方式导出,若是按照C++方式,Sum名称会被编译器自动修改,不信你把extern "C"
去掉,我用ida打开给你看一下,被修改为了 ?Sum@@YAHHH@Z
, 尴尬。工具
接下来把C++项目生成好的 ConsoleApplication1.dll
copy到C#的bin目录下,代码以下:spa
class Program { [DllImport("ConsoleApplication1.dll", CallingConvention = CallingConvention.Cdecl)] extern static int Sum(int a, int b); static void Main(string[] args) { var result = Sum(10, 20); Console.WriteLine($"10+20={result}"); Console.ReadLine(); } } ---- output ----- 10+20=30
咱们知道托管代码和非托管代码是两个世界,这中间涉及到了两个世界的的类型映射,那映射关系去哪找呢? 微软的msdn还真有一篇介绍 封送通用类型对照表: https://docs.microsoft.com/zh... ,你们有兴趣能够看一下。指针
从图中能够看到,C#中的string对应C++中的char*,因此这里就好处理了。code
--- Person.cpp extern "C" { //字符串 _declspec(dllexport) int GetLength(char* chs); } --- Person.h #include "Person.h" #include "iostream" using namespace std; int GetLength(char* chs) { return strlen(chs); }
而后咱们看一下C#这边怎么写,一般string在C++中使用asc码,而C#中是Unicode,因此在DllImport中加一个CharSet指定便可。orm
class Program { [DllImport("ConsoleApplication1.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] extern static int GetLength([MarshalAs(UnmanagedType.LPStr)] string str); static void Main(string[] args) { var str = "hello world"; Console.WriteLine($"length={GetLength(str)}"); Console.ReadLine(); } } ---- output ----- length=11
复杂类型配置对应关系就难搞了,还容易搞错,错了弄很差还内存泄漏,怕了吧,幸亏微软提供了一个小工具P/Invoke Interop Assistant
,它能够帮助咱们自动匹配对应关系,我就演示一个封送Person类的例子。
从图中能够看到,左边写好 C++
,右边自动给你配好C#
的映射类型,很是方便。
--- Person.cpp extern "C" { class Person { public: char* username; char* password; }; _declspec(dllexport) char* AddPerson(Person person); } --- Person.h #include "Person.h" #include "iostream" using namespace std; char* AddPerson(Person person) { return person.username; }
能够看到C++中AddPerson返回了char*,在C#中咱们用IntPtr来接,而后用Marshal将指针转换string,接下来用工具生成好的C#代码拷到项目中来,以下:
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct Person { /// char* [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] public string username; /// char* [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] public string password; } class Program { [DllImport("ConsoleApplication1.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] extern static IntPtr AddPerson(Person person); static void Main(string[] args) { var person = new Person() { username = "dotnetfly", password = "123456" }; var ptr = AddPerson(person); var str = Marshal.PtrToStringAnsi(ptr); Console.WriteLine($"username={str}"); Console.ReadLine(); } } ---------- output ------------ username=dotnetfly
前面介绍的3种状况都是单向的,即C#向C++传递数据,有的时候也须要C++主动调用C#的函数,咱们知道C#是用回调函数,也就是委托包装,具体我就不说了,很开心的是C++能够直接接你的委托,看下怎么实现。
--- Person.cpp extern "C" { //函数指针 typedef void(_stdcall* PCALLBACK) (int result); _declspec(dllexport) void AsyncProcess(PCALLBACK ptr); } --- Person.h #include "Person.h" #include "iostream" using namespace std; void AsyncProcess(PCALLBACK ptr) { ptr(10); //回调C#的委托 }
从代码中看到,PCALLBACK就是我定义了函数指针,接受int参数。
class Program { delegate void Callback(int a); [DllImport("ConsoleApplication1.dll", CallingConvention = CallingConvention.Cdecl)] extern static void AsyncProcess(Callback callback); static void Main(string[] args) { AsyncProcess((i) => { //这里回调函数哦... Console.WriteLine($"这是回调函数哦: {i}"); }); Console.ReadLine(); } } ------- output ------- 这是回调函数哦: 10
这里我作了一个自定义的delegate,由于我使用Action<T>
不接受泛型抛异常(┬_┬)。
这让我想起来前段时间用python实现的线性回归,为了简便我使用了http和C#交互,此次准备用C++改写而后PInvoke直接交互就利索了,好了,借助C++的生态,让 C# 如虎添翼吧~~~