自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

使用PInvoke互操作,讓C#和C++愉快的交互優(yōu)勢(shì)互補(bǔ)

開發(fā) 前端
很多硬件,視頻設(shè)備驅(qū)動(dòng)都是用C/C++實(shí)現(xiàn),然后用winform/WPF去做管理界面,C++還是在大學(xué)里學(xué)過(guò),好多年沒接觸了,為了練手這一篇用P/Invoke來(lái)將兩者相互打通。

一、背景

1. 講故事

如果你常翻看FCL的源碼,你會(huì)發(fā)現(xiàn)這里面有不少方法借助了C/C++的力量讓C#更快更強(qiáng)悍,如下所示:

[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);

聯(lián)想到上一篇阿里短信netsdk也是全用C++實(shí)現(xiàn),然后用C#做一層殼,兩者相互打輔助彰顯更強(qiáng)大的威力,還有很多做物聯(lián)網(wǎng)的朋友對(duì)這種.Net互操作技術(shù)太熟悉不過(guò)了,很多硬件,視頻設(shè)備驅(qū)動(dòng)都是用C/C++實(shí)現(xiàn),然后用winform/WPF去做管理界面,C++還是在大學(xué)里學(xué)過(guò),好多年沒接觸了,為了練手這一篇用P/Invoke來(lái)將兩者相互打通。

二、PInvoke互操作技術(shù)

1. 一些前置基礎(chǔ)

這里我用vs2019創(chuàng)建C++的Console App,修改兩個(gè)配置:將程序?qū)С鰹閐ll,修改成compile方式為Compile as C++ Code (/TP)。

圖片圖片

圖片圖片

2. 基本類型的互操作

簡(jiǎn)單類型是最好處理的,基本上int,long,double都是一一對(duì)應(yīng)的,這里我用C++實(shí)現(xiàn)了簡(jiǎn)單的Sum操作,畫一個(gè)簡(jiǎn)圖就是下面這樣:

圖片圖片

新建一個(gè)cpp文件和一個(gè)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;
}

有一個(gè)注意的地方就是 extern "C",一定要用C方式導(dǎo)出,如果按照C++方式,Sum名稱會(huì)被編譯器自動(dòng)修改,不信你把extern "C"去掉,我用ida打開給你看一下,被修改成了 ?Sum@@YAHHH@Z, 尷尬。

圖片圖片

接下來(lái)把C++項(xiàng)目生成好的 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

3. 字符串的互操作

我們知道托管代碼和非托管代碼是兩個(gè)世界,這中間涉及到了兩個(gè)世界的的類型映射,那映射關(guān)系去哪找呢?微軟的msdn還真有一篇介紹 封送通用類型對(duì)照表:https://docs.microsoft.com/zh-cn/dotnet/standard/native-interop/type-marshaling ,大家有興趣可以看一下。

圖片圖片

從圖中可以看到,C#中的string對(duì)應(yīng)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中加一個(gè)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

4. 復(fù)雜類型的處理

復(fù)雜類型配置對(duì)應(yīng)關(guān)系就難搞了,還容易搞錯(cuò),錯(cuò)了弄不好還內(nèi)存泄漏,怕了吧,幸好微軟提供了一個(gè)小工具P/Invoke Interop Assistant,它可以幫助我們自動(dòng)匹配對(duì)應(yīng)關(guān)系,我就演示一個(gè)封送Person類的例子。

圖片圖片

從圖中可以看到,左邊寫好 C++,右邊自動(dòng)給你配好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來(lái)接,然后用Marshal將指針轉(zhuǎn)換string,接下來(lái)用工具生成好的C#代碼拷到項(xiàng)目中來(lái),如下:

[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

5. 回調(diào)函數(shù)(異步)的處理

前面介紹的3種情況都是單向的,即C#向C++傳遞數(shù)據(jù),有的時(shí)候也需要C++主動(dòng)調(diào)用C#的函數(shù),我們知道C#是用回調(diào)函數(shù),也就是委托包裝,具體我就不說(shuō)了,很開心的是C++可以直接接你的委托,看下怎么實(shí)現(xiàn)。

--- Person.cpp

extern "C"
{
    //函數(shù)指針
    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);  //回調(diào)C#的委托
}

從代碼中看到,PCALLBACK就是我定義了函數(shù)指針,接受int參數(shù)。

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) =>
            {
                //這里回調(diào)函數(shù)哦...

                Console.WriteLine($"這是回調(diào)函數(shù)哦: {i}");
            });

            Console.ReadLine();
        }
    }

------- output -------  

這是回調(diào)函數(shù)哦: 10

這里我做了一個(gè)自定義的delegate,因?yàn)槲沂褂肁ction<T>不接受泛型拋異常(┬_┬)。

三、總結(jié)

這讓我想起來(lái)前段時(shí)間用python實(shí)現(xiàn)的線性回歸,為了簡(jiǎn)便我使用了http和C#交互,這次準(zhǔn)備用C++改寫然后PInvoke直接交互就利索了,好了,借助C++的生態(tài),讓 C# 如虎添翼吧~~~

責(zé)任編輯:武曉燕 來(lái)源: 一線碼農(nóng)聊技術(shù)
相關(guān)推薦

2009-09-01 15:24:59

C++、C#和JAVA

2015-07-21 12:44:18

eSDK華為

2011-05-18 18:05:47

C#C++

2012-05-30 09:37:52

SAPAriba云計(jì)算

2011-05-18 17:56:38

C#C++

2009-08-28 10:14:45

C#內(nèi)存泄露

2013-09-24 14:15:25

H3CSDN軟件定義網(wǎng)絡(luò)

2009-08-03 14:36:08

c#組件

2009-08-19 10:09:21

C#和C++

2013-07-26 15:38:28

上海斐訊IBM MobileF

2009-09-04 17:34:11

C#CC++

2021-01-19 11:54:33

RFID傳感器

2009-08-25 15:59:28

C#串口操作

2015-06-24 15:15:44

Wi-Fi運(yùn)營(yíng)Wi-FiOTT

2009-08-12 18:16:47

C#類型比較

2010-01-28 14:38:36

C++和C#、Java

2015-05-07 10:59:07

Wi-FiLTE

2009-09-01 09:38:45

COM互操作性

2009-04-10 13:57:50

C#C++Java
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)