I need to do use a specific method to get a job done - it cannot be any other method or assembly. The method takes the following parameters:
void method(bool* isOn) {/* Some code... */}
I try to use false for the the parameter 'isOn', but Visual Studio tells "Argument 1: cannot convert from type 'bool' to 'bool*'".
How do I convert/use bool* so that it will act appropriately?
Thanks in advance.
Edit: This is not a duplicate of Usefulness of bool* in C# because I am asking specifically about a conversion from a pointer to a type and a type itself. Also, the thread mentioned asks for the uses of bool*, but does not directly answer my question.
bool * is a pointer to a variable of type bool, not the bool value type. Meaning what you need to pass is the memory reference to a Boolean variable, not the boolean value type itself:
https://msdn.microsoft.com/en-us/library/z19tbbca.aspx
When you call the method, what you should be able to do is as follows:
bool isOn=false;
method(&isOn);
& address operator returns the memory address reference that the parameter appears to be requiring.
https://msdn.microsoft.com/en-us/library/sbf85k1c.aspx
Note, you may need to use unsafe context/compiler options for this to work, but assume you are already from what you've said.
You cannot pass false
, because constants do not have an address.
In order to pass a pointer to false
, make a variable, set it to false
, and use &
operator to take variable's address:
unsafe class Program {
static void foo(bool* b) {
*b = true;
}
static void Main(string[] args) {
bool x = false;
Console.WriteLine(x); // Prints false
foo(&x);
Console.WriteLine(x); // Prints true
}
}
Note how the method is allowed to change the variable through a pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With