我在c#中编写了一个使用OpenCL的应用程序。我想直接访问函数,而不是使用现有的包装器,就像我过去使用其他DLL一样。当我调用函数GetPlatformIDs时,我间歇性地得到以下错误:
AccessViolationException was unhandled
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
我最初认为我的DLL调用中存在错误,因此我尝试查看来自其他站点的其他示例和来自开源项目的代码,但所有这些示例都表现相同。如果代码可以通过初始调用,则其他所有内容都可以正常工作,但是在第一次调用时它会失败50%的时间。为了说明这个问题,我创建了以下简单的样本:
using System;
using System.Runtime.InteropServices;
namespace openclerrortest
{
class Program
{
[DllImport("OpenCL.dll", EntryPoint = "clGetPlatformIDs", ExactSpelling = true)]
internal extern static unsafe int _GetPlatformIDs(uint num_entries, IntPtr* platforms, uint* num_platforms);
static unsafe void Test()
{
uint numOfPlatforms;
int ec = _GetPlatformIDs(0, (IntPtr*)IntPtr.Zero.ToPointer(), &numOfPlatforms);
}
static void Main(string[] args)
{
Test();
}
}
}
崩溃时的堆栈跟踪:
at openclerrortest.Program._GetPlatformIDs(UInt32 num_entries, IntPtr* platforms, UInt32* num_platforms)
at openclerrortest.Program.Test() in C:\Users\Me\Documents\Visual Studio 2005\Projects\openclerrortest\openclerrortest\Program.cs:line 14
at openclerrortest.Program.Main(String[] args) in C:\Users\Me\Documents\Visual Studio 2005\Projects\openclerrortest\openclerrortest\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
非常感谢任何帮助。