我有一个封闭源代码的非托管DLL用C++编写,我想在C#解决方案中使用,所以我创建了一个使用P/Invoke调用封闭源代码DLL函数的包装管理DLL。对于没有param函数和int变量,这很好。但是,当运行一个更复杂的函数时,我得到一个System.ExecutionEngineException,该函数将一个结构数组作为参数包含字符串的char数组。这里是我有什么:P/Invoke throw System.ExecutionEngineException
[StructLayout(LayoutKind.Sequential)]
public struct Target
{
public int targetID;
public string Label;
}
[DllImport("tyrfde.dll", EntryPoint = "tyrfdeGetTarget")]
public static extern int GetTarget(ref Target[] targets);
下面是我从DLL的头文件有信息:
#define TARGET_LBL_SIZE (256l)
typedef struct _tyrfdeTarget
{
TInt32 TargetID; // integer signed 32bits
TCharA Label[TARGET_LBL_SIZE]; // caracter
} tyrfdeTarget;
TInt32 __stdcall tyrfdeGetTargets(tyrfdeTarget* pTargets);
不明白为什么数组的大小被指定为长,但无论如何SizeConst只取INT。经过一些搜索后,我试图修复。
[StructLayout(LayoutKind.Sequential, Size = 260), Serializable]
public struct Target
{
public int targetID;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 256)]
public string Label;
}
[DllImport("tyrfde.dll", EntryPoint = "tyrfdeGetTargets")]
public static extern int GetTarget(ref Target[] targets);
但我仍然有问题。我已经读过,如果函数清除CLR使用的部分内存,则可能抛出此异常。很遗憾,我无法证实这一点。我的代码中是否存在显然错误并可能导致问题的内容?
您还应该发布一个实际分配数组并调用该函数的示例。问题可能在那里。看起来奇怪的是,如果函数接受一个指向'N'元素的指针,它也不需要数组中元素的个数作为第二个参数。 – arul 2009-12-02 15:04:48