有关C#调用C++的dll的一些问题



2009-11-19 12:21 在c#里调用C++的dll时,需要注意的一些问题在c#里调用C++的dll,遇到了一些头疼的问题:

C++里头文件定义形势如下:

typedef void (*CALLBACKFUN1W)(wchar_t*, void* pArg);
typedef void (*CALLBACKFUN1A)(char*, void* pArg);

bool BIOPRINT_SENSOR_API dllFun1(CALLBACKFUN1 pCallbackFun1, void* pArg);

在其中一个导入的dll方法里,有一个回调函数的参数

[DllImport("test.dll", EntryPoint = "dllFunc1", CharSet = CharSet.Unicode)]
public static extern bool dllFunc1([MarshalAs(UnmanagedType.FunctionPtr)] CallbackFunc1 pCallbackFunc1 , IntPtr pArg);

回调函数在C#里定义成委托如下:
public delegate void CallbackFunc1(StringBuilder strName, IntPtr pArg);

调试运行,报错。
有时是直接出错退出,信息如下:
Buffer overrun detected!

Program:
...

A buffer overrun has been detected which has corrupted the program's internal state. The program cannot safely continue execution and must now be terminated.

有时则能运行起来,但会抛出异常:
System.AccessViolationException: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。

几经周折,觅得答案,原来是要指定 调用方式,如下就OK了:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void CallbackFunc1(IntPtr hWnd, IntPtr pArg);

而系统默认方式为 CallingConvention.StdCall。


程序终于不报错了,但是又出现结果不对了
定义成如下时,strName在方法中的值,只有一个字符,
public delegate void CallbackFunc1(StringBuilder strName, IntPtr pArg);

后来改为:
public delegate void CallbackFunc1([MarshalAs(UnmanagedType.LPWStr)] StringBuilder strName, IntPtr pArg);

OK了,strName带出来的值完整了,参数类型定义成 string 或者 StringBuilder 都无所谓

还可以用 IntPtr ,或者 char* 都行(用char* 得加 unsafe)

char* 类型的,得到值后,可循环至'\0'得到整个字符串
IntPtr 类型的,可以用Marshal.Copy出来,如:
Marshal.Copy(IntPtr_source, toBytes, 0, 1024);



如果报
“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”
异常,
还有可能是因为C++和C#的参数类型对应问题,

如:
bool __declspec(dllimport) getImage(unsigned char** ppImage, int& nWidth, int& nHeight);

对应成
[DllImport("test.dll")]
public static extern bool getImage(IntPtr ppImage, ref int nWidth, ref int nHeight);

时,
则该方法在调用前,要对传入的ppImage分配空间,如下
IntPtr pImage = Marshal.AllocHGlobal(iWidth * iHeight);
这种方法不推荐,因为是带出结果来,一般这种指针不确定需要分配多大空间的。

正确的要对应成下面这样:
[DllImport("test.dll")]
public static extern

bool getImage(ref IntPtr ppImage, ref int nWidth, ref int nHeight);

调用时只要定义就行了:
I
ntPtr pImage = new IntPtr();
int refWidth = 0, refHeight = 0;

getImage(ref pImage, ref refWidth, ref refHeight);

总结,凡是双针指类型参数,可以用 ref IntPtr
而对于 int*, int&, 则都可用 ref int 对应


另外,提一下自定义消息的响应

public const int WM_USER = 0x0400;
public const int WM_TEST_MSG = (WM_USER + 0x100);


C# 要响应 dll 的自定义 消息,则要重写 WinForm的DefWndProc方法。

protected override void DefWndProc(ref Message m)

{

switch (m.Msg)
{

case WM_TEST_MSG:
{

}
break;

default:
base.DefWndProc(ref m);
break;
}

}


消息发送是通过 Windows 提供的 API 函数 SendMessage 来实现的,它的原型定义:

[DllImport("User32.dll",EntryPoint="SendMessage")]
private static extern int SendMessage(
IntPtr hWnd, // handle to destination window
uint Msg, // message
uint wParam, // first message parameter
uint lParam // second message parameter
);



再转贴一篇相关文章:

C#中调用Windows API的要点

在.Net Framework SDK文档中,关于调用Windows API的指示比较零散,并且其中稍全面一点的是针对Visual Basic .net讲述的。本文将C#中调用API的要点汇集如下,希望给未在C#中使用过API的朋友一点帮助。另外如果安装了Visual Studio .net的话,在C:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Samples\Technologies\Interop\PlatformInvoke\WinAPIs\CS目录下有大量的调用API的例子。
一、调用格式
using System.Runtime.InteropServices; //引用此名称空间,简化后面的代码
...
//使用DllImportAttribute特性来引入api函数,注意声明的是空方法,即方法体为空。
[DllImport("user32.dll")]
public static extern ReturnType FunctionName(type arg1,type arg2,...);
//调用时与调用其他方法并无区别
可以使用字段进一步说明特性,用逗号隔开,如:
[ DllImport( "kernel32", EntryPoint="GetVersionEx" )]
DllImportAttribute特性的公共字段如下:
1、CallingConvention 指示向非托管实现传递方法参数时所用的 CallingConvention 值。
CallingConvention.Cdecl : 调用方清理堆栈。它使您能够调用具有 varargs 的函数。
CallingConvention.StdCall : 被调用方清理堆栈。它是从托管代码调用非托管函数的默认约定。
2、CharSet 控制调用函数的名称版本及指示如何向方法封送 String 参数。
此字段被设置为 CharSet 值之一。如果 CharSet 字段设置为 Unicode,则所有字符串参数在传递到非托管实现之前都转换成 Unicode 字符。这还导致向 DLL EntryPoint 的名

称中追加字母“W”。如果此字段设置为 Ansi,则字符串将转换成 ANSI 字符串,同时向 DLL EntryPoint 的名
称中追加字母“A”。
大多数 Win32 API 使用这种追加“W”或“A”的约定。如果 CharSet 设置为 Auto,则这种转换就是与平台有关的(在 Windows NT 上为 Unicode,在 Windows 98 上为 Ansi)。CharSet 的默认值为 Ansi。CharSet 字段也用于确定将从指定的 DLL 导入哪个版本的函数。
CharSet.Ansi 和 CharSet.Unicode 的名称匹配规则大不相同。对于 Ansi 来说,如果将 EntryPoint 设置为“MyMethod”且它存在的话,则返回“MyMethod”。如果 DLL 中没有“MyMethod”,但存在“MyMethodA”,则返回“MyMethodA”。
对于 Unicode 来说则正好相反。如果将 EntryPoint 设置为“MyMethod”且它存在的话,则返回“MyMethodW”。如果 DLL 中不存在“MyMethodW”,但存在“MyMethod”,则返回“MyMethod”。如果使用的是 Auto,则匹配规则与平台有关(在 Windows NT 上为 Unicode,在 Windows 98 上为 Ansi)。如果 ExactSpelling 设置为 true,则只有当 DLL 中存在“MyMethod”时才返回“MyMethod”。
3、EntryPoint 指示要调用的 DLL 入口点的名称或序号。
如果你的方法名不想与api函数同名的话,一定要指定此参数,例如:
[DllImport("user32.dll",CharSet="CharSet.Auto",EntryPoint="MessageBox")]
public static extern int MsgBox(IntPtr hWnd,string txt,string caption, int type);
4、ExactSpelling 指示是否应修改非托管 DLL 中的入口点的名称,以与 CharSet 字段中指定的 CharSet 值相对应。如果为 true,则当 DllImportAttribute.CharSet 字段设置为 CharSet 的 Ansi 值时,向方法名称中追加字母 A,当 DllImportAttribute.CharSet 字段设置为 CharSet 的 Unicode 值时,向方法的名称中追加字母 W。此字段的默认值是 false。
5、PreserveSig 指示托管方法签名不应转换成返回 HRESULT、并且可能有一个对应于返回值的附加 [out, retval] 参数的非托管签名。
6、SetLastError 指示被调用方在从属性化方法返回之前将调用 Win32 API SetLastError。 true 指示调用方将调用 SetLastError,默认为 false。运行时封送拆收器将调用 GetLastError 并缓存返回的值,以防其被其他 API 调用重写。用户可通过调用 GetLastWin32Error 来检索错误代码。
#c# 浏览(1057)评论转载
评论

500/0 同时评论给
同时评论给原文作者 发布
收起|查看更多
帮助中心 | 空间客服 | 投诉中心 | 空间协议?2012 Baidu

相关主题
相关文档
最新文档