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對於解決這個問題所給予的協助。