3
$\begingroup$

Suppose there is a Q# operation as follows:

operation Op () : Bool {

    let result = CSharpMethod ();
    return result
}

where CSharpMethod () is a defined method in the Driver class as follows:

public static bool CSharpMethod () {
    // ...
    // return a boolean value
}

So my question is how to call a method of a C# class inside a Q# operation and handle its returned value?

Thanks.

$\endgroup$

1 Answer 1

3
$\begingroup$

Q# operations are compiled into C# classes. To define a C# implementation for a Q# operation, you will need to do the following steps:

  1. Define a Q# operation with empty or intrinsic body CSharpMethod.
  2. Define a C# class that implements the abstract class into which your Q# operation gets compiled, something like public class CSharpMethod_Impl : CSharpMethod.
  3. Define method called Body in that class that does the actual computation that you need and returns the result.

This is a very hacky thing to do, so you might want to follow an example of operation GetOracleCallsCount and its C# implementation to see the exact pieces that have to be in place for it to work.

You can also see this question on StackOverflow that tries to do a similar thing.

$\endgroup$
2
  • $\begingroup$ Thanks for your time but my question is not about defining a C# implementation for a Q# operation, but it is about calling a C# method in the Q# operation. What I intend to do in this question is different from the purpose of the question to which you referred. $\endgroup$
    – Coder
    Jan 11, 2020 at 20:57
  • 1
    $\begingroup$ I understood that. There is no way to call a C# method from Q# directly without defining a Q# operation for it, so the approach I described is your best shot at getting it to work. $\endgroup$ Jan 12, 2020 at 1:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.