Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntPtr and avoiding unsafe code

Tags:

c#

.net

intptr

I have an external library that takes an IntPtr. Is there any safe way to do this...

int BytesWritten = 0;
Output.WriteBytes(buffer, new IntPtr(&BytesWritten));

...without having to use 'unsafe' code? I'm not that familiar with IntPtrs, but I'd like to do something like this:

fixed int BytesWritten = 0;
Output.WriteBytes(buffer, IntPtr.GetSafeIntPtr(ref BytesWritten));

...in such a way that I don't need to compile with /unsafe.

I can't change the WriteBytes function, it's an external function.

It seems like there should be some sort of cast between 'ref int' and IntPtr, but I have not had luck finding it.

like image 290
Aric TenEyck Avatar asked Jul 26 '10 17:07

Aric TenEyck


People also ask

What does unsafe code mean?

Unsafe code in general is a keyword that denotes a code section that is not handled by the Common Language Runtime(CLR). Pointers are not supported by default in C# but unsafe keyword allows the use of the pointer variables.

What is an unsafe and safe code?

In this article, we are going to learn about the unsafe code in C#. In general, the code that we write in C# is safe code. It creates managed objects and doesn't access the memory directly. On the other hand, unsafe code in C# is code that is not in direct control of the Common Language Runtime (CLR).

What is unsafe code in C sharp?

Unsafe code in C# isn't necessarily dangerous; it's just code whose safety cannot be verified. Unsafe code has the following properties: Methods, types, and code blocks can be defined as unsafe. In some cases, unsafe code may increase an application's performance by removing array bounds checks.

Which type is used in unsafe mode?

Now to understand what UnsafeMode is. Unsafe is a C# programming language keyword to denote a section of code that is not managed by the Common Language Runtime (CLR) of the . NET Framework, or unmanaged code. Unsafe is used in the declaration of a type or member or to specify a block code.


2 Answers

I assume that Output.WriteBytes is a [DllImport] method. Can you post the declaration?

You should be able to avoid the pointer by declaring the last parameter as out int instead of IntPtr -- let the P/Invoke marshaller do the rest.

like image 130
Tim Robinson Avatar answered Sep 27 '22 16:09

Tim Robinson


Yes, there is. You can use P/Invoke for your code. It will create the pointer for you automagically. Something like this:

[DllImport("yourlib", SetLastError=true)]
static extern bool WriteBytes(
    [MarshalAs(UnmanagedType.LPArray)]
    byte [] buffer,
    ref int BytesWritten);

(I added the array as a bonus). More info on P/Invoke can be found, with gazillion examples, at pinvoke.net.

Each parameter above can take out, in and ref. Out and ref parameters are translated as pointers, where an ref-parameter is two-way.

like image 42
Abel Avatar answered Sep 27 '22 16:09

Abel