1、数据类型转换
C++ C#
1)BOOL bool
2)char*(输入) string
3)char*(输出) stringBuilder
2、函数调用导致堆栈不对称,原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配
改 [DllImport("winmm.dll", EntryPoint = "sndPlaySoundA",)]
static extern bool sndPlaySoundA();
为[DllImport("winmm.dll", EntryPoint = "sndPlaySoundA", CallingConvention = CallingConvention.Cdecl)]
static extern bool sndPlaySoundA();
转载自:http://blog.csdn.net/wjeson/article/details/8263335
以下例子是我用C#调用VC dll中的函数的声明及使用方法:
1、using System.Runtime.InteropServices;//使用dll动态库和API函数必需
2、引入函数:
[DllImport("PmacNc.dll", CharSet = CharSet.Ansi)]
public static extern int GetResponse(StringBuilder com_response, System.UInt32 maxchar, System.Char[] sendChar);
C#调用VC dll输出参数的注意事项
1.CharSet要使用Ansi,因为Vc默认是Ansi的,而c#是Unicode,两者不统一会产生乱码。还有其他DIIImport的其他参数如下,除了EntryPoint,其他三个都是非必要的。
EntryPoint: 指定要调用的 DLL 入口点。默认入口点名称是托管方法的名称 。
CharSet: 控制名称重整和封送 String 参数的方式 (默认是UNICODE)
CallingConvention指示入口点的函数调用约定(默认WINAPI)
SetLastError 指示被调用方在从属性化方法返回之前是否调用 SetLastError Win32 API 函数 (C#中默认false )
2.结构体的引用传递
首先在c#中定义和c++相同的结构体,如果是引用传递,在结构体前面加上[In, Out],如:
[DllImport(@"test.dll")]
public static extern int test([In, Out] SLineData[] lndt,ref UInt32 length);
3.如果遇到char**类型的输出参数也就是指针的指针,或者二维数组或其他更复杂的情况。可以参考以下网页:
http://www.cppblog.com/kerlw/archive/2007/06/27/27061.html?opt=admin
http://www.ixpub.net/viewthread.php?tid=810850