使用PInvoke互操做,讓C#和C++愉快的交互優點互補

一:背景

1. 講故事

若是你常翻看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

二:PInvoke互操做技術

1. 一些前置基礎

這裏我用vs2019建立C++的Console App,修改兩個配置: 將程序導出爲dll,修改爲compile方式爲Compile as C++ Code (/TP)dom

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目錄下,代碼以下: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

2. 字符串的互操做

咱們知道託管代碼和非託管代碼是兩個世界,這中間涉及到了兩個世界的的類型映射,那映射關係去哪找呢? 微軟的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

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# 如虎添翼吧~~~

相關文章
相關標籤/搜索