C#調用c++類的匯出函數

來源:互聯網
上載者:User

標籤:步驟   log   不能   dllimport   ptr   void   目標   ret   ogr   

C# 需要調用C++東西,但是有不想做成COM,就只好先匯出類中的函數處理。

不能直接調用,需單獨匯出函數

參考:http://blog.csdn.net/cartzhang/article/details/9097043

c# 調用c++匯出類的一個樣本

參考:http://blog.csdn.net/huiyouyongdeyu2011/article/details/6547931

還沒測試此例子

 

以下是VS2010 C#調用C++ DLL檔案的例子

背景 

     在項目過程中,有時候你需要調用非C#編寫的DLL檔案,尤其在使用一些第三方通訊群組件的時候,通過C#來開發應用軟體時,就需要利用DllImport特性進行方法調用。本篇文章將引導你快速理解這個調用的過程。

步驟

1. 建立一個CSharpInvokeCPP的解決方案:

2. 建立一個C++的動態庫項目:

3. 在應用程式設定中,選擇“DLL”,其他按照預設選項:

最後點擊完成,得到項目:

      我們可以看到這裡有一些檔案,其中dllmain.cpp作為定義DLL應用程式的進入點,它的作用跟exe檔案有個main或者WinMain入口函數是一樣的,它就是作為DLL的一個入口函數,實際上它是個可選的檔案。它是在靜態連結時或動態連結時調用LoadLibrary和FreeLibrary時都會被調用。詳細內容可以參考(http://blog.csdn.net/benkaoya/archive/2008/06/02/2504781.aspx)。

4. 現在我們開啟CSharpInvokeCPP.CPPDemo.cpp檔案:

現在我們加入以下內容:

1 // CSharpInvokeCPP.CPPDemo.cpp : 定義 DLL 應用程式的匯出函數。

2  //
3  
4 #include "stdafx.h"

6  extern "C" __declspec(dllexport) int Add(int x, int y)
7 {
8 return x + y;
9 }
10  extern "C" __declspec(dllexport) int Sub(int x, int y)
11 {
12 return x - y;
13 }
14  extern "C" __declspec(dllexport) int Multiply(int x, int y)
15 {
16 return x * y;
17 }
18  extern "C" __declspec(dllexport) int Divide(int x, int y)
19 {
20 return x / y;
21 }

 

      extern "C" 包含雙重含義,從字面上即可得到:首先,被它修飾的目標是“extern”的;其次,被它修飾的目標是“C”的。而被extern "C"修飾的變數和函數是按照C語言方式編譯和串連的。

      __declspec(dllexport)的目的是為了將對應的函數放入到DLL動態庫中。

      extern "C" __declspec(dllexport)加起來的目的是為了使用DllImport調用非託管C++的DLL檔案。因為使用DllImport只能調用由C語言函數做成的DLL。

5. 編譯項目程式,最後在Debug目錄產生CSharpInvokeCPP.CPPDemo.dll和CSharpInvokeCPP.CPPDemo.lib

我們用反編譯工具PE Explorer查看下該DLL裡面的方法:

可以發現對外的公用函數上包含這四種“加減乘除”方法。

6. 現在來示範下如何利用C#項目來調用非託管C++的DLL,首先建立C#控制台應用程式:

7. 在CSharpInvokeCSharp.CSharpDemo項目上建立一個CPPDLL類,編寫以下代碼:

1 public class CPPDLL

2 {
3 [DllImport("CSharpInvokeCPP.CPPDemo.dll")]
4 public static extern int Add(int x, int y);

6 [DllImport("CSharpInvokeCPP.CPPDemo.dll")]
7 public static extern int Sub(int x, int y);

9 [DllImport("CSharpInvokeCPP.CPPDemo.dll")]
10 public static extern int Multiply(int x, int y);
11 
12 [DllImport("CSharpInvokeCPP.CPPDemo.dll")]
13 public static extern int Divide(int x, int y);
14 }

 

DllImport作為C#中對C++的DLL類的匯入入口特徵,並通過static extern對extern “C”進行對應。

8. 另外,記得把CPPDemo中產生的DLL檔案拷貝到CSharpDemo的bin目錄下,你也可以通過設定【項目屬性】->【配置屬性】->【常規】中的輸出目錄:

這樣編譯項目後,產生的檔案就自動輸出到CSharpDemo中了。

9. 然後在Main入口編寫測試代碼:

1 static void Main(string[] args)

2 {
3 int result = CPPDLL.Add(10, 20);
4 Console.WriteLine("10 + 20 = {0}", result);

6 result = CPPDLL.Sub(30, 12);
7 Console.WriteLine("30 - 12 = {0}", result);

9 result = CPPDLL.Multiply(5, 4);
10 Console.WriteLine("5 * 4 = {0}", result);
11 
12 result = CPPDLL.Divide(30, 5);
13 Console.WriteLine("30 / 5 = {0}", result);
14 
15 Console.ReadLine();
16 }

 

運行結果:

方法得到調用。 

10. 以上的方法只能通過靜態方法對於C++中的函數進行調用。那麼怎樣通過靜態方法去調用C++中一個類對象中的方法呢?現在我在CPPDemo項目中添加一個標頭檔userinfo.h: 

1 class UserInfo {

2  private:
3 char* m_Name;
4 int m_Age;
5  public:
6 UserInfo(char* name, int age)
7 {
8 m_Name = name;
9 m_Age = age;
10 }
11 virtual ~UserInfo(){ }
12 int GetAge() { return m_Age; }
13 char* GetName() { return m_Name; }
14 };

 

在CSharpInvokeCPP.CPPDemo.cpp中,添加一些代碼:

1#include "malloc.h"

2#include "userinfo.h"
3
4typedef struct {
5 char name[32];
6 int age;
7} User;
8
9UserInfo* userInfo;
10
11extern "C" __declspec(dllexport) User* Create(char* name, int age)
12{
13 User* user = (User*)malloc(sizeof(User));
14
15 userInfo = new UserInfo(name, age);
16 strcpy(user->name, userInfo->GetName());
17 user->age = userInfo->GetAge();
18
19 return user;
20}

這裡聲明一個結構,包括name和age,這個結構是用於和C#方面的結構作個映射。

注意:代碼中的User*是個指標,返回也是一個對象指標,這樣做為了防止方法範圍結束後的局部變數的釋放。

strcpy是個複製char數組的函數。

11. 在CSharpDemo項目中CPPDLL類中補充代碼:

1 [DllImport("CSharpInvokeCPP.CPPDemo.dll")]

2  public static extern IntPtr Create(string name, int age);

4 [StructLayout(LayoutKind.Sequential)]
5  public struct User
6 {
7 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
8 public string Name;

10 public int Age;
11 }

 

其中這裡的結構User就和C++中的User對應。

12. 在Program.cs中補充代碼: 

1 IntPtr ptr = CPPDLL.Create("李平", 27);

2  CPPDLL.User user =(CPPDLL.User)Marshal.PtrToStructure(ptr, typeof(CPPDLL.User));
3 Console.WriteLine("Name: {0}, Age: {1}", user.Name, user.Age); 

注意:這裡結構指標首先轉換成IntPtr控制代碼,然後通過Marshal.PtrToStructrue轉換成你所需要的結構。

運行結果:

 

C#調用c++類的匯出函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.