[Mono-dev] trouble with mono's handling of "unsafe struct pointers" vs MS.NET...

David Jeske davidj at gmail.com
Fri Aug 17 20:16:01 UTC 2012


I have a C# wrapper for a native DLL which exists on both windows and UNIX.
However, it doesn't work on Mono because of a behavior difference between
Mono and MS.NET.

Specifically, I use "unsafe struct pointers" to manage pointers to opaque
data (rather than IntPtr). I do this to get typechecking, because
there area bunch of types of pointers, and using IntPtr is dangerously
non-type-checked. (I honestly don't undertand why IntPtr is allowed, rather
than always requiring the use of typed unsafe-struct-pointers.)  As far as
I know, CLR/CTS defines an unsafe-struct-pointer as a value type.

http://stackoverflow.com/questions/4503795/is-it-valid-to-use-unsafe-struct-as-an-opaque-type-instead-of-intptr-in-net-p

My code looks something like:

// opaque types
public unsafe struct HDF {};

// NEOERR* hdf_set_value (HDF *hdf, char *name, char *value)
[DllImport("libneo")]
private static unsafe extern NEOERR* hdf_set_value(HDF *hdf,
     [MarshalAs(UnmanagedType.LPStr)]
      string name,
     [MarshalAs(UnmanagedType.LPStr)]
      string value);

This works fine in MS.NET, but Mono complains with the following error:

Unhandled Exception: System.Runtime.InteropServices.MarshalDirectiveException:
Can not marshal 'parameter #1': Pointers can not reference marshaled
structures. Use byref instead.
  at (wrapper managed-to-native) Clearsilver.Hdf:hdf_set_value (Clearsilver.
HDF*,string,string)
  at Clearsilver.Hdf.setValue (System.String name, System.String value)
[0x00000]
  at CSTest.Main (System.String[] argv) [0x00000]

My questions:

(1) Why is Mono complaining about this? AFAIK, in the CLR, an unsafe
structpointer is not a marshalled structure, it's a value type.

(2) Why would it suggest using ByRef? ByRef is for managed pointers to
managed data. This is a value-type pointer value.  AFAIK, ByRef is not
capable of doing anything here, because the pointer is just a "typed"
IntPtr value type.

(3) I think this used to work in older versions of mono. Is there some
particular reason the behavior has changed? Do folks agree this is a
problem?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.ximian.com/pipermail/mono-devel-list/attachments/20120817/52445a8b/attachment-0001.html>


More information about the Mono-devel-list mailing list