I have an unmanaged DLL with a function that takes a pointer as an argument. How do I pass a pointer from C# without being 'unsafe'?
Here's some example code:
[DllImport(@"Bird.dll")]
private static extern bool foo(ushort *comport);
The corresponding entry in the header:
BOOL DLLEXPORT foo(WORD *pwComport);
When I try and simply dereference it (&comport
), I get an error saying: "Pointers and fixed size buffers may only be used in an unsafe context."
How do I work around this?
Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points.
There are three ways to pass variables to a function – pass by value, pass by pointer and pass by reference.
When we pass a pointer as an argument instead of a variable then the address of the variable is passed instead of the value. So any change made by the function using the pointer is permanently made at the address of passed variable. This technique is known as call by reference in C.
Use ref
:
[DllImport(@"Bird.dll")]
private static extern bool foo(ref ushort comport);
Call it like so:
ushort comport;
foo(ref comport);
For interop like this, I'd prefer to use UInt16
rather than ushort
as the equivalent to WORD
.
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