[Mono-dev] "safe" way about Marshal.UnsafeAddrOfPinnedArrayElement

Jonathan Pryor jonpryor at vt.edu
Tue Apr 18 07:48:11 EDT 2006


On Tue, 2006-04-18 at 12:27 +0800, GaoXianchao wrote:
> hi all,
> I'm wrapping epoll api on linux.
> To pass address of managed struct array to unmanaged code, I use
> Marshal.UnsafeAddrOfPinnedArrayElement . But the method is "unsafe".
> Is there a "safe" way to do what the Marshal.UnsafeAddrOfPinnedArrayElement do?

It's "unsafe" because you need to be careful. :-)

An alternative is to use *real* unsafe code, e.g.

	FooStruct[] array = ...;
	unsafe {
		fixed (FooStruct* pArray = array) {
			FooStruct* element = &pArray [index];
		}
	}

I'm not entirely sure what your problem is though.  "Unsafe" code (like
the above `unsafe' block) just means that you're possibly executing
without a net, which could result in memory corruption and abortion of
the process. :-)

Marshal.UnsafeAddrOfPinnedArrayElement isn't even in an unsafe C#
context, it just has "Unsafe" in the name.

Here's a hint of truth: ANY time you do a P/Invoke, you're potentially
doing something unsafe. :-)

(Especially considering that you're invoking external code which could
really do anything, such as overwrite the entire GC heap, which would
cause the process an ugly death in the future...)

However, I'm not sure why you need
Marshal.UnsafeAddrOfPinnedArrayElement in the first place.
epoll_wait(2) takes a `struct epoll_event' array parameter, so unless
you wanted to only send a subset of your array, the default marshaling
rules which convert a managed array to an array pointer should be fine.

 - Jon





More information about the Mono-devel-list mailing list