C#调用C++ dll时参数传递编译不通过

FoxBryant 2014-11-14 07:20:13
各位大神,我按如下方法调用C++ dll的导出函数,编译时总是提示调用参数无数,请问可能是什么问题呢?

C++函数原型:
int Plat_GetAllControlCell(
int iUserHandle,
int iNeedGetNum,
LPPLAT_CONTROLCELLINFO pCellBuffer,
int* pOutputNum);

其中LPPLAT_CONTROLCELLINFO是结构指针。

我声明的C#对应函数为:
[DllImport("PlatformSDK.dll", EntryPoint = "Plat_GetAllControlCell", CallingConvention = CallingConvention.Cdecl)]
public static extern int Plat_GetAllControlCell(
int iUserHandle,
int iNeedGetNum,
ref PLAT_CONTROLCELLINFO pCellBuffer,
ref int pOutputNum
);

我的调用方法:
int PlatRtnCell = 0;
PlatInterface.Plat_GetAllControlCell(g_iLoginHandle, 0, null, ref PlatRtnCell); //g_iLoginHandle是int类型的成员变量


非常感谢您的帮助!
...全文
169 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
FoxBryant 2014-11-16
  • 打赏
  • 举报
回复
以下是解决代码: [DllImport("PlatformSDK.dll", EntryPoint = "Plat_GetAllControlCell", CallingConvention = CallingConvention.Cdecl)] public static extern int Plat_GetAllControlCell( int iUserHandle, int iNeedGetNum, IntPtr cellInfoPtr, //对应C++的结构指针 ref int pOutputNum ); 调用时如果结构指针传空,则使用: IntPtr ptrNull = IntPtr.Zero; Plat_GetAllControlCell(iHandle, 0, ptrNull, ref x);
FoxBryant 2014-11-16
  • 打赏
  • 举报
回复
谢谢各位的回复,问题已经解决了。传结构指针时,对应到C#也应该用指针,参考下面的网址: http://www.tuicool.com/articles/uEnyMb 在项目开发时,要调用C++封装的DLL,普通的类型C#上一般都对应,只要用DllImport传入从DLL中引入函数就可以了。但是当传递的是结构体、结构体数组或者结构体指针的时候,就会发现C#上没有类型可以对应。这时怎么办,第一反应是C#也定义结构体,然后当成参数传弟。然而,当我们定义完一个结构体后想传递参数进去时,会抛异常,或者是传入了结构体,但是返回值却不是我们想要的,经过调试跟踪后发现,那些值压根没有改变过,代码如下。 [DllImport("workStation.dll")] private static extern bool fetchInfos(Info[] infos); public struct Info { public int OrderNO; public byte[] UniqueCode; public float CpuPercent; }; private void buttonTest_Click(object sender, EventArgs e) { try { Info[] infos=new Info[128]; if (fetchInfos(infos)) { MessageBox.Show("Fail"); } else { string message = ""; foreach (Info info in infos) { message += string.Format("OrderNO={0}\r\nUniqueCode={1}\r\nCpu={2}", info.OrderNO, Encoding.UTF8.GetString(info.UniqueCode), info.CpuPercent ); } MessageBox.Show(message); } } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } 后来,经过查找资料,有文提到对于C#是属于托管内存,现在要传递结构体数组,是属性非托管内存,必须要用Marsh指定空间,然后再传递。于是将结构体变更如下。 [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] public struct Info { public int OrderNO; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] UniqueCode; public float CpuPercent; }; 但是经过这样的改进后,运行结果依然不理想,值要么出错,要么没有被改变。这究竟是什么原因?不断的搜资料,终于看到了一篇,里面提到结构体的传递,有的可以如上面所做,但有的却不行,特别是当参数在C++中是结构体指针或者结构体数组指针时,在C#调用的地方也要用指针来对应,后面改进出如下代码。 [DllImport("workStation.dll")] private static extern bool fetchInfos(IntPtr infosIntPtr); [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] public struct Info { public int OrderNO; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] UniqueCode; public float CpuPercent; }; private void buttonTest_Click(object sender, EventArgs e) { try { int workStationCount = 128; int size = Marshal.SizeOf(typeof(Info)); IntPtr infosIntptr = Marshal.AllocHGlobal(size * workStationCount); Info[] infos = new Info[workStationCount]; if (fetchInfos(infosIntptr)) { MessageBox.Show("Fail"); return; } for (int inkIndex = 0; inkIndex < workStationCount; inkIndex++) { IntPtr ptr = (IntPtr)((UInt32)infosIntptr + inkIndex * size); infos[inkIndex] = (Info)Marshal.PtrToStructure(ptr, typeof(Info)); } Marshal.FreeHGlobal(infosIntptr); string message = ""; foreach (Info info in infos) { message += string.Format("OrderNO={0}\r\nUniqueCode={1}\r\nCpu={2}", info.OrderNO, Encoding.UTF8.GetString(info.UniqueCode), info.CpuPercent ); } MessageBox.Show(message); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } 要注意的是,这时接口已经改成IntPtr了。通过以上方式,终于把结构体数组给传进去了。不过,这里要注意一点,不同的编译器对结构体的大小会不一定,比如上面的结构体 在BCB中如果没有字节对齐的话,有时会比一般的结构体大小多出2两个字节。因为BCB默认的是2字节排序,而VC是默认1 个字节排序。要解决该问题,要么在BCB的结构体中增加字节对齐,要么在C#中多开两个字节(如果有多的话)。字节对齐代码如下。 #pragma pack(push,1) struct Info { int OrderNO; public char UniqueCode[32]; float CpuPercent; }; #pragma pack(pop) 用Marsh.AllocHGlobal为结构体指针开辟内存空间,目的就是转变化非托管内存,那么如果不用Marsh.AllocHGlobal,还有没有其他的方式呢? 其实,不论C++中的是指针还是数组,最终在内存中还是一个一个字节存储的,也就是说,最终是以一维的字节数组形式展现的,所以我们如果开一个等大小的一维数组,那是否就可以了呢?答案是可以的,下面给出了实现。 [DllImport("workStation.dll")] private static extern bool fetchInfos(IntPtr infosIntPtr); [DllImport("workStation.dll")] private static extern bool fetchInfos(byte[] infos); [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] public struct Info { public int OrderNO; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] UniqueCode; public float CpuPercent; }; private void buttonTest_Click(object sender, EventArgs e) { try { int count = 128; int size = Marshal.SizeOf(typeof(Info)); byte[] inkInfosBytes = new byte[count * size]; if (fetchInfos(inkInfosBytes)) { MessageBox.Show("Fail"); return; } Info[] infos = new Info[count]; for (int inkIndex = 0; inkIndex < count; inkIndex++) { byte[] inkInfoBytes = new byte[size]; Array.Copy(inkInfosBytes, inkIndex * size, inkInfoBytes, 0, size); infos[inkIndex] = (Info)bytesToStruct(inkInfoBytes, typeof(Info)); } string message = ""; foreach (Info info in infos) { message += string.Format("OrderNO={0}\r\nUniqueCode={1}\r\nCpu={2}", info.OrderNO, Encoding.UTF8.GetString(info.UniqueCode), info.CpuPercent ); } MessageBox.Show(message); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } #region bytesToStruct /// <summary> /// Byte array to struct or classs. /// </summary> /// <param name=”bytes”>Byte array</param> /// <param name=”type”>Struct type or class type. /// Egg:class Human{...}; /// Human human=new Human(); /// Type type=human.GetType();</param> /// <returns>Destination struct or class.</returns> public static object bytesToStruct(byte[] bytes, Type type) { int size = Marshal.SizeOf(type);//Get size of the struct or class. if (bytes.Length < size) { return null; } IntPtr structPtr = Marshal.AllocHGlobal(size);//Allocate memory space of the struct or class. Marshal.Copy(bytes, 0, structPtr, size);//Copy byte array to the memory space. object obj = Marshal.PtrToStructure(structPtr, type);//Convert memory space to destination struct or class. Marshal.FreeHGlobal(structPtr);//Release memory space. return obj; } #endregion
Saleayas 2014-11-14
  • 打赏
  • 举报
回复
public static extern  int Plat_GetAllControlCell(int iUserHandle, int iNeedGetNum, [Out, MarshalAs(LPArray, SizeParamIndex=1)] PLAT_CONTROLCELLINFO pCellBuffer[], [Out]ref int pOutputNum) ;
我更加觉得 C++ 参数 的 Buffer 是期望一个数组。
hwangt0 2014-11-14
  • 打赏
  • 举报
回复
接口中 ref PLAT_CONTROLCELLINFO pCellBuffer 把ref去掉
wanghui0380 2014-11-14
  • 打赏
  • 举报
回复
没仔细看工具转换出来滴
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet=System.Runtime.InteropServices.CharSet.Ansi)]
public struct PLAT_CONTROLCELLINFO {
    
    /// int
    public int iControlCellID;
    
    /// int
    public int iParentCellID;
    
    /// char[128]
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=128)]
    public string csControlCellName;
}

public partial class NativeMethods {
    
    /// Return Type: int
    ///iUserHandle: int
    ///iNeedGetNum: int
    ///pCellBuffer: LPPLAT_CONTROLCELLINFO->_tagControlCellInfo*
    ///pOutputNum: int*
    [System.Runtime.InteropServices.DllImportAttribute("<Unknown>", EntryPoint="Plat_GetAllControlCell")]
public static extern  int Plat_GetAllControlCell(int iUserHandle, int iNeedGetNum, ref PLAT_CONTROLCELLINFO pCellBuffer, ref int pOutputNum) ;

}
hwangt0 2014-11-14
  • 打赏
  • 举报
回复
PLAT_CONTROLCELLINFO pCellBuffer = new PLAT_CONTROLCELLINFO();
int PlatRtnCell = 0;
PlatInterface.Plat_GetAllControlCell(g_iLoginHandle, 0, pCellBuffer, ref PlatRtnCell); 
new个结构体了再传
FoxBryant 2014-11-14
  • 打赏
  • 举报
回复
C++声明的结构体如下: typedef struct _tagControlCellInfo { int iControlCellID; int iParentCellID; char csControlCellName[128]; }PLAT_CONTROLCELLINFO, *LPPLAT_CONTROLCELLINFO; 我转换成C#的声明是: public struct PLAT_CONTROLCELLINFO { public int iControlCellID; public int iParentCellID; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)] public byte[] csControlCellName; }
xian_wwq 2014-11-14
  • 打赏
  • 举报
回复
结构体传空不行,因为在函数中要赋值 1. 把 LPPLAT_CONTROLCELLINFO 结构体的转换贴出来看看。 2.可以把 CallingConvention = CallingConvention.Cdecl改成CallingConvention.Stdcall再试试

110,538

社区成员

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

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

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