Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 236
Tom Wright Avatar asked Mar 30 '11 19:03

Tom Wright


People also ask

What is passing pointer to a function in C?

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.

How many ways can you pass pointer to a function?

There are three ways to pass variables to a function – pass by value, pass by pointer and pass by reference.

Can you pass the address of a pointer?

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.


1 Answers

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.

like image 134
David Heffernan Avatar answered Sep 22 '22 03:09

David Heffernan