Tom Wright
Tom Wright

Reputation: 11479

How can I pass a pointer from C# to an unmanaged DLL?

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?

Upvotes: 5

Views: 5272

Answers (1)

David Heffernan
David Heffernan

Reputation: 612854

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.

Upvotes: 13

Related Questions