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

28次阅读

共计 4205 个字符,预计需要花费 11 分钟才能阅读完成。

一:背景

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…,大家有兴趣可以看一下。

从图中可以看到,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# 如虎添翼吧~~~

正文完
 0