调用c++ DLL 返回结构体问题

jinxuliang 2007-12-14 12:07:19
(1)我要调用c++ 写的Setting.dll中的FindConverter函数,其返回得到的设备信息。
(2)程序能编译过,但执行的时候说堆栈溢出,可能有死循环。我用c++调用很正常。因为没有setting.dll的代码,所以没办法改写。请高人指教。


//程序源码如下
namespace ResetModal
{
public class Win32
{
[StructLayout(LayoutKind.Sequential)]
public struct CONVINFO
{
public string strMac;
public string strIP;
public UInt16 devType;


};
[DllImport(@"E:\study\ResetModal\ResetModal\Setting.dll", CharSet = CharSet.Auto)]
public static extern int FindConverter( CONVINFO [] pConvInfo, int count,bool bEnableMsg,Int32 timeout);
[DllImport(@"E:\study\ResetModal\ResetModal\Setting.dll", CharSet = CharSet.Auto)]
public static extern bool ResetConverter(string strMAC,bool bEnableMsg,Int32 timeout);
}

class Program
{

static void Main(string[] args)
{
//
int count = 200;
Win32.CONVINFO [] _convInfo=new Win32.CONVINFO[200];

{

Win32.FindConverter( _convInfo, count, true, 3000);
Win32.ResetConverter(_convInfo[0].strMac, true, 1000);

}


}
}
}
...全文
322 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
真相重于对错 2007-12-14
  • 打赏
  • 举报
回复
传递数组可以用System.IntPtr
CONVINFO[] CI = new .....
System.IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement( CI,0);
jinxuliang 2007-12-14
  • 打赏
  • 举报
回复
to:zhbo2001
问题的关键在于我要传入的是
int count = 200;

Win32.CONVINFO [] _convInfo=new Win32.CONVINFO[200];

//我需要的是一个结构体数组,而不是单一的变量引用
int ret = Findconverter(ref pConvInfo, count, bEnableMsg, timeout);

zhbo2001 2007-12-14
  • 打赏
  • 举报
回复
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CONVINFO
{
[MarshalAs(UnmanagedType.ByValTstr, SizeConst=20]
public string strMac;
[MarshalAs(UnmanagedType.ByValTstr, SizeConst=20]
public string strIP;
public UInt16 devType;


};

[DllImport(@"E:\study\ResetModal\ResetModal\Setting.dll", CharSet = CharSet.Auto)]
public static extern int FindConverter(ref CONVINFO pConvInfo, int count,bool bEnableMsg, Int32 timeout);


CONVIINFO pConvInfo;
int count;
bool bEnableMsg;
Int32 timeout;

int ret = Findconverter(ref pConvInfo, count, bEnableMsg, timeout);
真相重于对错 2007-12-14
  • 打赏
  • 举报
回复
托管和非托管传递数据,要求双方必须了解,数据的内存布局。你上面的方式有可能有问题,
1、字符串的编码不正确
2、数组的长度不符合要求
msdn search 平台调用 ,看看吧。
jinxuliang 2007-12-14
  • 打赏
  • 举报
回复
有没有高人留个mail,我发给你帮我看看
jinxuliang 2007-12-14
  • 打赏
  • 举报
回复

////////////////////////////按如下C++中调用Setting.dll没有任何问题
//头文件声明形式
typedef struct _CONVINFO
{
char strMAC[20]; //转换器MAC地址,格式为00.09.F6.01.02.03
char strIP[20]; //转换器IP地址,格式为10.1.1.1
WORD devType; //转换器型号
}CONVINFO;
__declspec(dllimport) int _stdcall FindConverter(CONVINFO *pConvInfo,int count,BOOL bEnableMsg,DWORD timeout);

c++中调用形式

CONVINFO m_convInfoTable[1000];
int count=FindConverter(m_convInfoTable,m_maxConvCnt,TRUE,3000);
for (int i=0;i<count;i++)
{
//进行处理

}
qgmzhfj 2007-12-14
  • 打赏
  • 举报
回复
结构体里的数据类型对嘛?
zhbo2001 2007-12-14
  • 打赏
  • 举报
回复
应该把C++调用的代码贴出来

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧