当前位置:首页 > C# > 正文内容

使用PInvoke互操作,让C#和C++愉快的交互优势互补

admin12个月前 (04-05)C#1540

一:背景

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://link.zhihu.com/?target=https%3A//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<T>不接受泛型抛异常(┬_┬)。

四:总结

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

扫描二维码推送至手机访问。

版权声明:本文由视觉博客发布,如需转载请注明出处。

本文链接:https://feelsight.cn/post/141.html

“使用PInvoke互操作,让C#和C++愉快的交互优势互补” 的相关文章

c# 全局鼠标事件

1.Win32Api public class Win32Api { [StructLayout(LayoutKind.Sequential)] public class POINT { publi...

C#全局监听Windows键盘事件

1.工具类代码 using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Windows...

C# 窗体间传值(Form与From之间互相传值)

C# 窗体间传值(Form与From之间互相传值)

1、委托   两个窗体,窗体很简单,只实现改变颜色功能,一看就会: 代码如下,只贴按钮事件代码: 打开Form2按钮事件 private void button1_Click(object s...

高恪路由器批量管理监控系统

高恪路由器批量管理监控系统

一、采用C# 编写,可以批量监控路由器是否正常 功能: 1.显示当前路由IP、名字、实时上行速度、实时下行速度、主机数量、连接数、CPU占用率、内存占用率、CPU温度、运行时间等 2.可以显示10分钟实时流量 3.可以显示历史2小时、...

c# 委托实现多线程的实例/另一个class类调用控件

c# 委托实现多线程的实例/另一个class类调用控件

一、使用线程在窗体中显示进度条 在Winform应用程序中,经常用进度条显示进度信息。这时候就可能用到多线程。如果不采用多线程控制进度条的话,窗口界面很容易假死(无法看到进度信息,看起来像界面卡住了)。 在这个实例中,我们建立一个窗体,窗体中包括一个后台组件,一个进度条控件。当在主窗...

c#程序闪退日志记录/异常日志

以下代码是程序入口文件 using DDS_Form1; using System; using System.Collections.Generic; using System.IO; //using System.Linq; using System.Windows.Forms;...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。