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

  • Home
  • SEARCH
  • 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 1897898
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T06:42:05+00:00 2026-05-17T06:42:05+00:00

I have a c# .net 2.0 CF application that interfaces with a native DLL

  • 0

I have a c# .net 2.0 CF application that interfaces with a native DLL implementing a function like this:

struct NATIVE_METHOD_REPLY
{
    int other_irrelevant_data;
    int data_size;
    void* data;
}

// reply_buffer will contain an array of NATIVE_METHOD_REPLY structures
// and their data.
//
// returns an error code
int Foo(NATIVE_METHOD_REPLY* reply_buffer, int reply_size);

I’ve implemented it in C# like this:

[StructLayout(LayoutKind.Sequential)]
internal struct NATIVE_METHOD_REPLY
{
    public Int32 OtherIrrelevantData;
    public Int16 DataSize;
    public IntPtr DataPtr;
}

[DllImport("my_lib.dll", SetLastError = true)]
internal static extern Int32 Foo(byte[] replyBuffer, Int32 replySize);

public byte[] void Bar()
{
    // data returned to the user. May be an arbitrary size.
    byte[] result_buffer = new byte[256];

    // data sent to Foo() 
    byte[] reply_buffer = 
        new byte[Marshal.SizeOf(typeof(NativeMethods.NATIVE_METHOD_REPLY)) + 
            result_buffer.Length];

    NativeMethods.Foo(reply_buffer, reply_buffer.Length);

    // is there a better way of doing this?

    NativeMethods.NATIVE_METHOD_REPLY reply;
    GCHandle pinned_reply = GCHandle.Alloc(reply_buffer, 
        GCHandleType.Pinned);
    try
    {
        reply = (NativeMethods.NATIVE_METHOD_REPLY)Marshal.PtrToStructure(
            pinned_reply.AddrOfPinnedObject(), 
            typeof(NativeMethods.NATIVE_METHOD_REPLY));

        Marshal.Copy(reply.DataPtr, result_buffer, 0, reply.DataSize);
    }
    finally
    {
        pinned_reply.Free();
    }

    // bonus point*: is this okay to do after the Free() call?
    int test = reply.OtherIrrelevantData;

    return result_buffer;
}

While this works correctly, I would like to know if this is the most efficient / most correct way of implementing this function.

Is there some method converting a managed byte array to a managed structure that doesn’t involve an intermediate native handle and a copy? For instance, in C++, I would just do this:

NATIVE_METHOD_REPLY* reply = reinterpret_cast< NATIVE_METHOD_REPLY* >( reply.DataPtr );

*For a bonus point, is it okay to use data in the structure after the native handle has been freed?

Thanks,
PaulH


Edit: Updated solution

[DllImport("my_lib.dll", SetLastError = true)]
internal static extern Int32 Foo(IntPtr replyBuffer, Int32 replySize);

public byte[] void Bar()
{
    byte[] result_buffer = new byte[256];

    int reply_buffer_len = Marshal.SizeOf(typeof(NativeMethods.NATIVE_METHOD_REPLY)) + result_buffer.Length;
    IntPtr reply_buffer = Marshal.AllocCoTaskMem(reply_buffer_len);
    NativeMethods.NATIVE_METHOD_REPLY reply;

    try        
    {
        NativeMethods.Foo(reply_buffer, reply_buffer_len);

        reply = (NativeMethods.NATIVE_METHOD_REPLY)Marshal.PtrToStructure(
            reply_buffer, 
            typeof(NativeMethods.NATIVE_METHOD_REPLY));

        Marshal.Copy(reply.DataPtr, result_buffer, 0, reply.DataSize);
    }
    finally
    {
        Marshal.FreeCoTaskMem(reply_buffer);
    }

    return result_buffer;
}
  • 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-17T06:42:06+00:00Added an answer on May 17, 2026 at 6:42 am

    The structure has a fixed size. There’s no point in passing an array, just pass the structure:

    [DllImport("my_lib.dll", SetLastError = true)]
    internal static extern Int32 Foo(out NATIVE_METHOD_REPLY replyBuffer, Int32 replySize);
    

    You do have a memory management problem. Who owns the pointer?


    Okay, the structure is actually variable sized and the pointer points into the array. You need nother approach. Simply allocate a chunk of unmanaged memory up front instead of letting the P/Invoke marshaller copy the data into a managed array. Which is in fact a hard requirement since the garbage collector can move the array, invalidating the pointer. Call Marshal.CoTaskMemAlloc() to reserve the memory, you’ll have to free it later. And change the first argument of the function to IntPtr (not out).

    You’ll find that marshaling the structure a lot easier too, no need to pin the memory. Don’t forget to Marshal.FreeCoTaskMem() when you’re done.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a .NET application that contains a checkbox (System.Windows.Forms.Checkbox). This component (WindowsForms10.BUTTON.app.0.378734a1) is
I have an asp.net / c# application that interfaces with the database only through
I have .NET application that is hosted on IIS 6.1 It is impossible to
I have a .NET application that I want to use as a client to
We have a .net application that we didn't develop, but use. I can tell
I have a .Net application that dynamically creates a small HTML page and pops
I have a .NET application that uses some API calls, for example GetPrivateProfileString .
I have a .net application that is not working on a colleagues computer (he
Here's the core problem: I have a .NET application that is using COM interop
I have an ASP.NET application that is hosted in timezone A and is being

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.