5

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?

Tom Wright
  • 11,278
  • 15
  • 74
  • 148

1 Answers1

13

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490