这是我得到执行错误的行:
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。我非常不确定发生了什么。请帮助我!
最佳答案
您的 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
传递数组,您将传递一个指向指针的指针。换句话说,一级间接太过分了。
另一种思考方式是您要求非托管代码创建托管数组。而这显然是它做不到的。
关于c# - DllImport 期间出现 FatalExecutionEngineError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22966893/