之前我们讨论过如何用C#调用delphi生成的dll来获取计算机的硬件信息:如CPU序列号、硬盘序列号,这一章我们将讨论如何用C#调用C++生成的dll来获取计算机的硬件信息,在进入主题之前,我们有必要了解一下C#调用C++dll的使用方法及注意事项。
该dll返回的是一个字符串,但是由于C++函数不能直接返回字符串,它只能返回一个指针类型供C#接收,所以,我们可以采用以下形式: C++ 返回char*,C#用 IntPtr 来接收,只要得到指针的首地址,就可以得到整个字符串了。
我们就先通过一个简单的两个整数相加的实例来描述这一dll生成及调用过程。
1、新建项目,选择 Visual C++ 》 Win32项目 》 输入项目名称compute,在向导里选择 "下一步" 》应用程序类型 》选择 "dll" 》 完成。
2、新建头文件,取名compute.h,声明_declspec(dllexport) 导出 DLL 函数,代码如下:
extern "C" _declspec(dllexport) char* Add(int x, int y);
3、打开compute.cpp文件,在该文件下写函数体:
// compute.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include "compute.h"
#include <iostream>
using namespace std;
char* Add(int x, int y)
{
int value = x + y;
char arr[255] = {};
sprintf_s(arr,"the result is: %d",value);
string s = arr;
char* c;
const int len = s.length();
c = new char[len+1];
strcpy_s(c,len+1,s.c_str());
return c;
}
4、编译项目,生成compute.dll。
5、新建C#项目,把刚才生成的compute.dll复制到目录bin\Debug下。
6、引compute.dll,并调用
//引用dll
[DllImport("compute.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
static extern IntPtr Add(int x, int y);
//调用
IntPtr n = Add(100, 10);
string str = Marshal.PtrToStringAnsi(n);
Console.WriteLine(str);
测试结果为:the result is: 110
至此,就完成了一个简单的示例程序,在下一节我们将讲解如何用C++来获取计算机的硬件信息,并生成dll供C#调用。
在引用dll的时候,一定要注意下面这段文字:
Is the unmanaged C++ dll a debug build that needed some debug dependency files loaded on the test machines? Please
get a release build of the dll and test again.
Please download filemon and regmon from www.sysinternals.com to see which file is "access denied" or "not found" when called from asp.net.