我在玩Q#,它使用C#作为驱动程序。我想将Qubit对象传递给Q#代码,但它并不像预期的那样工作。
C#驱动程序
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
namespace Quantum.QSharpApplication1 {
class Driver {
static void Main(string[] args) {
using (var sim = new QuantumSimulator()) {
var x = new Microsoft.Quantum.Simulation.Common.QubitManager(10);
Qubit q1 = x.Allocate();
Solve.Run(sim, q1, 1);
}
System.Console.WriteLine("Press any key to continue...");
System.Console.ReadKey();
}
}
}Q#
namespace Quantum.QSharpApplication1
{
open Microsoft.Quantum.Primitive;
open Microsoft.Quantum.Canon;
operation Solve (q : Qubit, sign : Int) : ()
{
body
{
let qp = M(q);
if (qp != Zero)
{
X(q);
}
H(q);
}
}
}当我运行它时,它没有错误地运行,直到到达System.Console.*行,此时它会在Q#代码中抛出以下异常
System.AccessViolationException
HResult=0x80004003
Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>调试器将此与Q#中的"let = M(q);“行关联。
注意,这确实发生在Solve.Run调用中,真正的代码有多个解题调用,并且输出看起来是正确的。只有在离开“使用QuantumSimulator”作用域后,才会出现这种情况。我记得我读到,Qubit在发布之前必须被重置为零。我不确定这是否是问题所在,但我在C#中找不到这样的方法。有趣的是,我删除了控制台行,程序将无错误地运行(计时?)
发布于 2018-07-02 19:37:24
用于创建量子位的QubitManager实例不是单例(每个Simulator都有自己的QubitManager),因此Simulator不知道您试图在Q#代码上操作的Qubit,因此是AccessViolationException。
通常,不支持在驱动程序上创建量子位;您可以在borrowing中使用Q#语句。建议是在Q#中创建一个入口点来分配执行量子位分配的量子位,并从驱动程序调用它,例如:
// MyOp.qs
operation EntryPoint() : ()
{
body
{
using (register = Qubit[2])
{
myOp(register);
}
}
}
// Driver.cs
EntryPoint.Run().Wait();最后,请注意,在您的驱动程序代码中有以下内容:Solve.Run(sim, q1, 1);
Run方法返回异步执行的任务。您通常必须添加一个Wait()以确保它完成执行:EntryPoint.Run(sim, 1).Wait();
如果您这样做,您将注意到在Run,而不是Console.WriteLine期间的失败。
https://stackoverflow.com/questions/51116480
复制相似问题