Alex Rivera | Logout

C# how can i pin an object in memory without marshalling the object?

Asked 2011-02-28T14:38:39.457
13

Ok here it goes, i'm using oracle's ContentAccess library in C#, the library is programmed in C.

I use some functions of the library to extract text from diffrent files. the c library uses async communication by function pointers (Delegates). i have 1 class and 1 struct that is needed to use the functions, the struct is called BaseIO and contains functions pointers that points to my code in C# to read files. everything is fine, until cli moves my class, and i get an MemoryAccessException.

here is the class, struct and function signature:

[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
public delegate DAERR CloseDelegate(IntPtr hfile);
[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
public delegate DAERR ReadDelegate(IntPtr hfile, IntPtr dataPtr, UInt32 size, IntPtr count);
[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
public delegate DAERR WriteDelegate(IntPtr hfile, IntPtr dataPtr, int size, IntPtr count);
[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
public delegate DAERR SeekDelegate(IntPtr hfile, int wFrom, int dwOffset);
[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
public delegate DAERR TellDelegate(IntPtr hfile, IntPtr dwOffset);
[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
public delegate DAERR GetInfoDelegate(IntPtr hfile, UInt32 dwInfoId, IntPtr pInfo);
[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
public delegate DAERR Seek64Delegate(IntPtr hfile, ushort wFrom, Int64 dwOffset);
[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
public delegate DAERR Tell64Delegate(IntPtr hfile, Int64 dwOffset);

struct BaseIO
{
    public CloseDelegate IOCLOSEPROC;
    public ReadDelegate IOREADPROC;
    public WriteDelegate IOWRITEPROC;
    public SeekDelegate IOSEEKPROC;
    public TellDelegate IOTELLPROC;
    public GetInfoDelegate IOGETINFOPROC;
    public IntPtr IOOPENPROC;
    public Seek64Delegate IOSEEK64PROC;
    publi
Edit
Report

1 Answer

18

In C#, there are two ways to pin an object in memory: the fixed statement and GCHandle.Alloc. In your case, I believe you want GCHandle.Alloc.

See GCHandle.Alloc for a code example, and the fixed keyword documentation.

answered 2011-04-03T00:30:38.693

Your Answer