Search code examples
c#quantum-computingq#

How to pass C# array into a Q# operation within QuantumSimulator Run() command?


I'm making a program which uses an array of integers taken in as a parameter from the C# script in Driver.cs but it gives the following error:

Error CS1503 Argument 2: cannot convert from 'long[]' to 'Microsoft.Quantum.Simulation.Core.IQArray<long>'

I have tried to instead pass in an array of strings and convert them inside the program, but an identical error appears:

Error CS1503 Argument 2: cannot convert from 'string[]' to 'Microsoft.Quantum.Simulation.Core.IQArray<string>'

Here is the C# code in Driver.cs - keyArray is the array that I'm trying to pass to Q#.

using (var qsim = new QuantumSimulator())
{
    var result = QMain.Run(qsim, keyArray).Result;
    var (res0, res1, res2) = result;
    System.Console.WriteLine(res0 + ", " + res1 + ", " + res2);
}

Q# QMain operation in Operations.qs:

operation QMain(keyCode : Int[]) : (Result, Result, Result)

In Q#, Int datatype corresponds to C# long.

Passing an array of strings failed as well, with the following signature of QMain:

operation QMain(s : String[]) : (Result, Result, Result)

All that I'm getting is the same error whenever I try to use any array as a parameter in QMain.


Solution

  • The data type used for passing fixed-length arrays to and from Q# code is QArray. You have to create an instance of this data type from your array explicitly before passing it to QMain:

    var result = QMain.Run(qsim, new QArray<long>(keyArray)).Result;
    

    You can see an example of passing arrays to Q# in the samples.