下面是执行错误的行:
NimbieImportedFunctions.BS_Robots_Connect(
out robotCount, out robotIDs, out robotTypes, out robotReadys);
而DllImport本身:
[DllImport("BSRobots20.DLL", CallingConvention = CallingConvention.Cdecl)]
public static extern UInt32 BS_Robots_Connect(
out int nRobotCount,
out int[] pnRobotIDS,
out int[] pnRobotTypes,
out bool[] pbRobotReadys);
并从头文件:
extern "C" __declspec(dllexport) DWORD BS_Robots_Connect(
int *nRobotCount,
int *pnRobotID,
int *pnRobotType,
bool *pnRobotReady
);
//
// Description:
// Function to connect all online robots.
//
// Parameters:
// nRobotCount [out] Pointer to an integer that receives the number of robots.
// pnRobotID [out] Pointer to an array of integer that receives the robot IDs.
// pnRobotType [out] Pointer to an array of integer that receives the robot types.
//
// Return:
// BS_ROBOTS_OK If the function succeeds with no error.
// BS_ROBOTS_ERROR If the function fails with any error occurred.
//
///////////////////////////////////////////////////////////////////////////////
我所犯的错误是:
The runtime has encountered a fatal error. The address of the error was
at 0x72c4898e, on thread 0xdf0. The error code is 0xc0000005.
This error may be a bug in the CLR or in the unsafe or non-verifiable portions
of user code. Common sources of this bug include user marshaling errors for
COM-interop or PInvoke, which may corrupt the stack.
有时,我也会得到一个AccessViolationException。我非常不确定到底发生了什么。请帮帮我!
发布于 2014-04-09 15:36:20
您的p/invoke不正确。它或许应改为:
[DllImport("BSRobots20.DLL", CallingConvention = CallingConvention.Cdecl)]
public static extern uint BS_Robots_Connect(
out int nRobotCount,
[Out] int[] pnRobotIDS,
[Out] int[] pnRobotTypes,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U1)]
[Out] bool[] pbRobotReadys
);
nRobotCount
应该是ref
而不是out
,这是合理的。根据是否需要将信息传递到函数来确定这一点。你确定pbRobotReadys
是一个数组吗?如果没有,那么使用out bool
或ref bool
。
所以也许你需要的是:
[DllImport("BSRobots20.DLL", CallingConvention = CallingConvention.Cdecl)]
public static extern uint BS_Robots_Connect(
ref int nRobotCount,
[Out] int[] pnRobotIDS,
[Out] int[] pnRobotTypes,
[MarshalAs(UnmanagedType.U1)]
out bool pbRobotReadys
);
为了深入了解这一点,您需要进一步研究文档,并可能参考您可以找到的任何C++示例代码。
在调用函数之前,您需要分配数组。从这里我不知道你需要如何分配数组。想必你知道它们需要有多大。
为什么你的版本错了?那么,考虑这一点的方法是,C#数组已经是一个引用。通过使用out
传递数组,您就是将指针传递给指针。换句话说,一个层次的间接太远了。
考虑这一点的另一种方法是,您要求非托管代码创建托管数组。这是它显然做不到的事情。
https://stackoverflow.com/questions/22966893
复制相似问题