智能设备的C#和C++的混合项目开发心得(非托管的DLL函数调用)

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对于解决这个问题所给予的帮助。

原文地址:https://www.cnblogs.com/xuesong/p/1755232.html