DllImport在C#

时间:2018-11-14 19:51:51

标签: c# c++ dllimport

我过去曾经使用过DllImport,但是由于参数类型的原因,试图找出正确的声明和使用特定方法的方式会遇到很多麻烦。这是C ++原型:

//  PTRobot_EnumRobots
//
//  Description:
//      Function to enumerate the Robots on the system.
//  Params:
//      phRobots    points to an array of HANDLEs to store
//                  the Robots found.
//      pdwNumRobots    points to a DWORD containing the number of HANDLEs
//                  in the phRobots array.  This value is an input
//                  and an output.  The user should specify the size
//                  (number of HANDLEs) of the phRobots array on input.
//                  The value of the pdwNumRobots on output will be the
//                  number of robots found.
//
//  Notes:
//      Both params will be updated upon successful completion of this
//      command.  phRobots will contain handles to robots connected to
//      this system. pdwNumRobots will will be updated with the number of 
//      robots found.
//      Also, note that the hDrives[] array in the PTRobotInfo will not be
//      valid until PTRobot_EnumDrives is called.
//
//  Return:
//      PTROBOT_OK if Successful
//      PTROBOT_INVALID_ROBOT if no robots found
//      PTROBOT_SEQUENCE if this command is called out of sequence
//      PTROBOT_INTERNAL if an internal error occurred
//      PTROBOT_OVERFLOW if the number of robots found is > the value in 
//                       pdwNumRobots
//
///////////////////////////
DWORD WINAPI PTRobot_EnumRobots(HANDLE * phRobots, DWORD * pdwNumRobots);

这是C ++的用法:

HANDLE hRobots[10];
DWORD dwRet=0, dwRobots=10;

dwRet = PTRobot_EnumRobots(hRobots, &dwRobots);

这是我在C#中声明的尝试:

[DllImport("PTRobot.dll", CharSet = CharSet.Unicode)]
private static extern uint PTRobot_EnumRobots(ref IntPtr[] phRobots, ref uint pdwNumRobots);

用法:

IntPtr[] robotArray = new IntPtr[1];
UInt32 numRobots = 1;

status = PTRobotDLL.EnumRobots(ref robotArray, ref numRobots);

但是我认为这是不对的,因为即使C ++中该方法返回了“ OK”,我仍然不断返回“ INVALID_ROBOT”。我认为问题在于尝试写回这些引用时,可能是因为我不确定如何声明它们。

是否对使用C#声​​明方法的正确方法有任何见解?尤其是对于奇数的HANDLE数组引用?

0 个答案:

没有答案