在Windows Phone專案中呼叫C語言寫的DLL
最近接到一個需求,需要在WP裡呼叫一個C語言寫的DLL,並且說Android和iOS都可以,問我WP是否可以這樣? 我說我調研一下,就有了下面的文章。
在傳統C# WinForm 裡呼叫Win32 DLL都不容易(可能用慣了C#),要用P/Invoke,然後DllImport什麼什麼,那WP裡不是更麻煩?
先看看網上有沒有可用的文章,結果還真找到devdiv中的文章,但其中有兩處錯誤,所以我fix bug並且整理一下,然後展示給大家。
1.1、建立"模擬"C語言生成DLL的工程
1.2、建立好project後, 就看到兩個與之相同名稱的檔案
1.3、在.h檔案裡寫入
#pragma once extern "C" int _declspec(dllexport)Multiplication(int i, int j);
1.4、在.cpp檔案裡寫入
#include "pch.h" #include "CalculatorDynamicLinkLibrary.h" int Multiplication(int i, int j) { int calc = i * j; return calc; }
1.5、編譯這個project,在solution資料夾找到Debug,然後就能看到我們模擬生成的DLL
2.1、建立 C++ Windows Runtime Component 專案
2.2、建立好project後, 就看到兩個與之相同名稱的檔案
2.3、在.h檔案裡寫入
#pragma once #include <collection.h> #include <../CalculatorDynamicLinkLibrary/CalculatorDynamicLinkLibrary.h> namespace CalculatorInvoke { public ref class CalculatorInvoker sealed { public: CalculatorInvoker(); int Mult(int i, int j); }; }
2.4、在.cpp檔案裡寫入
#include "pch.h" #include "CalculatorInvoke.h" using namespace CalculatorInvoke; using namespace Platform; CalculatorInvoker::CalculatorInvoker() { } int CalculatorInvoker::Mult(int i, int j) { return Multiplication(i, j); }
如果這時你著急編譯,肯定會出錯,不信就試試,呵呵!
2.5、在component project上,右鍵屬性,找到設定Linker,在Additional Dependencies裡填寫第一個project的lib檔案
devdiv網站是教的是設定.dll檔案,我試了會報錯
2.6、設定General,這裡一定不能錯,不然就會報找不到.lib檔案。devdiv教的是指向絕對路徑,如果把專案移到別的目錄下還會報找不到.lib路徑。
點Additional Library Directories 的下拉,再點Edit,就彈出如下視窗
Tips:關於類似”$(SolutionDir)“的用法,已經在連結3中給出了,列舉比較詳情,感謝作者!
3.1、建立 Windows Phone 專案,這裡是大家最熟悉的部分了
3.2、新增引用Windows Phone Component專案,或者後期引用Windows Phone Component生成出來的DLL也行。
3.3、新增Win32 DLL檔案到Windows Phone專案中,並在屬性裡設定為conent, copy always。
3.4、新增WP裡C#的程式碼
private void CalculateRsult(object sender, System.Windows.Input.GestureEventArgs e) { if (string.IsNullOrWhiteSpace(input1.Text) || string.IsNullOrWhiteSpace(input2.Text)) { MessageBox.Show("輸入框不能為空!", "友情提示", MessageBoxButton.OK); return; } CalculatorInvoker calculator = new CalculatorInvoker(); int i = Convert.ToInt32(this.input1.Text); int j = Convert.ToInt32(this.input2.Text); int result = calculator.Mult(i, j); this.txtResult.Text = string.Format("{0}", result); }
編譯步驟:先CalculatorDynamicLinkLibrary,再CalculatorInvoker,最後CalculatorApp
3.5、計算結果
參考文件:
http://www.devdiv.com/forum.php?mod=viewthread&tid=135252
http://www.jarredcapellman.com/2012/11/03/how-to-get-c-winrt-in-a-windows-phone-8-application/
http://www.cnblogs.com/lidabo/archive/2012/05/29/2524170.html