日期:2014-05-20  浏览次数:20733 次

c#调用com的函数声明(一解决立给分)
函数原型:
int   __stdcall   Abc(UINT   us,   USHORT   usMaxLength,   BYTE   *pData,   USHORT   *usLength);

小弟在c#声明中写成:
[DllImport( "AA.dll ",   CallingConvention   =   CallingConvention.StdCall)]
public   unsafe   static   extern   int   Abc(uint   us,   ushort   usMaxLength,   byte[]   pData,   ref   ushort   usLength);

可是在vs03中运行会提示NullReference异常,vs05中会提示Attempted   to   read   or   write   protected   memory.   This   is   often   an   indication   that   other   memory   is   corrupt异常

但是在vc非夸平台调用代码:
BYTE   pBuffer[512];
USHORT   usLen   =   512;
int   rv   =   Abc(1,   usLen,   pBuffer,   &usLen);
则正常运行。

现在小弟想在net下调用该dll,请问该如何写c#的函数声明呢,请高手帮忙给出详细代码。

一解决立给分。

------解决方案--------------------
声明没什么问题,你的pData记得初始化了吧?

ushort len = 256;
byte[] pData = new byte[256];
int rv = Abc(1, len, pData, ref len);
------解决方案--------------------
lz:记得你以前发过类似的帖子:
http://community.csdn.net/Expert/topic/5339/5339700.xml?temp=4.096621E-02

你这个接口是普通的dll,不是com组件,在com的IDL规范里,根本不会允许出现:UINT ,USHORT,。。。这样的类型,这些都是MFC用typedef得到专用类型,其他非VC平台是不会识别的。

普通的dll,可以如下转换:
[DllImport( "AA.dll ", CallingConvention = CallingConvention.StdCall)]
public unsafe static extern int Abc(uint us, ushort usMaxLength, IntPtr pData, ref ushort usLength);


ushort len = 256;
byte[] pData = new byte[256];

IntPtr ptr=IntPtr.Zero;
int rv = Abc(1, len, ptr, ref len);
Marshal.PtrToStructure(ptr,pData);