Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 551701
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T11:25:18+00:00 2026-05-13T11:25:18+00:00

This is code example which causes MarshalDirectiveException. Good explanation of SafeHandle s could be

  • 0

This is code example which causes MarshalDirectiveException. Good explanation of SafeHandles could be found here.


[SuppressUnmanagedCodeSecurity]
private delegate SafeHandle testDelegate();

[SuppressUnmanagedCodeSecurity]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static SafeHandle test(){
    FileStream fs=new FileStream("a.txt", FileMode.Create);
    return fs.SafeFileHandle;
}

private static void Main(){
    MethodInfo methodInfo = typeof (Program).GetMethod("test", BindingFlags.Static | BindingFlags.Public);
    Delegate delegateInstance = Delegate.CreateDelegate(typeof (testDelegate), methodInfo);

    //System.Runtime.InteropServices.MarshalDirectiveException
    //Cannot marshal 'return value': SafeHandles cannot be returned from managed to unmanaged.
    IntPtr fcePtr = Marshal.GetFunctionPointerForDelegate(delegateInstance);

    // alternatively for method parameter
    // throws System.Runtime.InteropServices.MarshalDirectiveException 
    // Cannot marshal 'parameter #1': This type can only be marshaled in restricted ways."

    // alternatively for HandleRef
    // System.Runtime.InteropServices.MarshalDirectiveException
    // Cannot marshal 'parameter #1': HandleRefs cannot be marshaled ByRef or from unmanaged to managed.
}

Simply said, naked handle, received as int or IntPtr could be leaking, when exception is throws before wrapped to appropriate Dipose patter. When returning naked handle to native code, it tends to be g-collected before native code uses the handle. I’m interested to learn how to workaround this problem with enough safety. Specially returning handle worries me. These are just examples for brevity, I don’t work with File handle in reality. I would rather like inherit my own from SafeHandle.


[DllImport("mydll")]
public static extern void naked(IntPtr nakedHandle);

private static void Main(){
    IntPtr intPtr = getHandle();
    naked(intPtr);
}

private static IntPtr getHandle(){
    FileStream fs = new FileStream("myfile", FileMode.CreateNew);
    IntPtr ha = fs.Handle;
    return ha;
    // at this point, fs is garbage collected. 
    // ha is pointing to nonexistent or different object.
}

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T11:25:19+00:00Added an answer on May 13, 2026 at 11:25 am

    The typical way to handle this is by pinning the data in the managed code before calling unmanaged functions. Here is an example of pinning data and calling unmanaged calls.

    Update: Based on the comment, you could use HandleRef to keep the object reference alive. Then you can still pass the “Handle” to your PInvoke calls. Here is an example that worked for me:

      [DllImport("kernel32.dll", SetLastError=true)]
      static extern bool ReadFile(HandleRef hFile, byte[] lpBuffer,
         uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped);
    
      private static HandleRef getHandle()
      {
         FileStream fs = new FileStream("myfile", FileMode.OpenOrCreate, FileAccess.ReadWrite);
         return new HandleRef(fs, fs.SafeFileHandle.DangerousGetHandle());
      }
    
      private static void Main()
      {
         HandleRef intPtr = getHandle();
         GC.Collect();
         GC.WaitForPendingFinalizers();
         GC.Collect();
         System.Threading.Thread.Sleep(1000);
    
         const uint BYTES_TO_READ = 10;
         byte[] buffer = new byte[BYTES_TO_READ];
         uint bytes_read = 0;        
    
         bool read_ok = ReadFile(intPtr, buffer, BYTES_TO_READ, out bytes_read, IntPtr.Zero);
         if (!read_ok)
         {
            Win32Exception ex = new Win32Exception();
            string errMsg = ex.Message;
         }
      }
    

    Almost forgot about clean up here:

      IDisposable is_disposable = intPtr.Wrapper as IDisposable;
      if (is_disposable != null)
      {
         is_disposable.Dispose();
      }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 295k
  • Answers 295k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer You can use an anonymous function in matlab (similar to… May 13, 2026 at 6:49 pm
  • Editorial Team
    Editorial Team added an answer The rule of thumb for any application is to let… May 13, 2026 at 6:49 pm
  • Editorial Team
    Editorial Team added an answer Just released Jinja 2.3 has experimental support for Python 3.… May 13, 2026 at 6:49 pm

Related Questions

I have a problem with the background compiler in Delphi7: in my project there
I have two forms, form A and form B. These forms must differ in
I am poking around the animation in WPF and I am confused. For RectAnimation,
I'm trying to understand how grep works in this example. The code works but
In one part of the application I'm working on, there is a form control

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.