使用PInvoke互操作,让C#和C++愉快的交互优势互补(pinvoke调用不对称)

网友投稿 270 2022-08-16

使用PInvoke互操作,让C#和C++愉快的交互优势互补(pinvoke调用不对称)

一:背景

1. 讲故事

如果你常翻看FCL的源码,你会发现这里面有不少方法借助了C/C++的力量让C#更快更强悍,如下所示:

[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来将两者相互打通。

二:PInvoke互操作技术

1. 一些前置基础

这里我用vs2019创建C++的Console App,修改两个配置: 将程序导出为dll,修改成compile方式为Compile as C++ Code (/TP)。

2. 基本类型的互操作

简单类型是最好处理的,基本上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目录下,代码如下:

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

2. 字符串的互操作

我们知道托管代码和非托管代码是两个世界,这中间涉及到了两个世界的的类型映射,那映射关系去哪找呢? 微软的msdn还真有一篇介绍 封送通用类型对照表: https://docs.microsoft.com/zh-cn/dotnet/standard/native-interop/type-marshaling ,大家有兴趣可以看一下。

从图中可以看到,C#中的string对应C++中的char*,所以这里就好处理了。

--- 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指定即可。

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

3. 复杂类型的处理

复杂类型配置对应关系就难搞了,还容易搞错,错了弄不好还内存泄漏,怕了吧,幸好微软提供了一个小工具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

4. 回调函数(异步)的处理

前面介绍的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不接受泛型抛异常(┬_┬)。

四:总结

这让我想起来前段时间用python实现的线性回归,为了简便我使用了http和C#交互,这次准备用C++改写然后PInvoke直接交互就利索了,好了,借助C++的生态,让 C# 如虎添翼吧~~~

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:https://www.ancii.com/amh64d6g4/
下一篇:C# 数据操作系列 - 19 FreeSql 入坑介绍
相关文章

 发表评论

暂时没有评论,来抢沙发吧~