智慧型裝置的C#和C++的混合項目開發心得(非託管的DLL函數調用)

來源:互聯網
上載者:User

1.開發環境描述

        OS Windows 7

        SDK: Windows Mobile 6.5.3 Professional DTK

        Development Environment: Visual Studio 2008

部署裝置為: Windows Mobile 6.5.3 Professional Emulator

2. 開發智慧型裝置的C#和C++項目遇到的問題描述

為了使得視頻檔案加入到工程中作為資源檔一起編譯,將播放視頻檔案的這段c++代碼建立一個dll,然後為這個dll建立一個.Net 的wrapper,這時您就可以添加引用這個wrapper,然後用C#調用這個dll了。在C#工程中可以通過添加視頻檔案,然後修改"Build Action"的值修改為Resource的方法將視頻檔案加入到工程.

該解決方案中使用C++來編寫非託管的DLL函數,然後通過P/Invoke在C#中進行調用。

    2.1. 在C#的工程中加入C++產生的DLL檔案,然後採用如下的方式調用此DLL

internal class SamplePlayerWrapper

{

[DllImport("SamplePlayer.dll")]

internal static extern void SamplePlayerDll(int nShowCmd);

}

public LearnSample()

{

InitializeComponent();

}

private void RunSamplePlayer()

{

try

{

int nShowCmd = 5;

SamplePlayerWrapper.SamplePlayerDll(nShowCmd);

}

catch (Exception e)

{

throw (e);

}

}

private void LearnSample_Load(object sender, EventArgs e)

{

RunSamplePlayer();

}

    2.2. 在C++工程中定義DLL API的方式如下:

#define DLLAPI extern "C" __declspec(dllexport)

DLLAPI int SamplePlayerDll(int nShowCmd);

  2.3. 在運行時報錯:“Can't find PInvoke DLL ‘SamplePlayer.dll”

3. 解決辦法

問題的關鍵是此C#的智慧型裝置工程如何成功Find這個PInvoke DLL。

    3.1. 設定將DLL檔案的位置,修改的C#的代碼如下

     [DllImport(@".\SamplePlayer.dll")]

    3.2. 將DLL檔案拷貝到工程目錄下,然後將DLL檔案加入到工程,並將DLL檔案的屬性“產生操作”設定為“內容”。

    Debug調試OK,調用正常。

在解決此問題時尋找到有的文章說使用絕對路徑來調用dll,從上文測試的結論可以看出在Windows Mobile 6.5.3中DLL設定為相對路徑也是可以的,重要的是路徑設定正確。

在此特別感謝微軟Jiang Tao Liu MSFT對於解決這個問題所給予的協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.