将字节数组从本机方法转换为托管结构

发布于 2024-09-25 06:46:59 字数 2849 浏览 5 评论 0原文

我有 ac# .net 2.0 CF 应用程序,它与实现如下功能的本机 DLL 接口:

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);

我已经在 C# 中实现了它,如下所示:

[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;
}

虽然它工作正常,但我想知道这是否是最有效/最正确的实现该功能的方法。

是否有某种方法将托管字节数组转换为不涉及中间本机句柄和副本的托管结构?例如,在 C++ 中,我会这样做:

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

*作为奖励点,在释放本机句柄后可以使用结构中的数据吗?

谢谢, PaulH


编辑:更新的解决方案

[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;
}

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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不寐倦长更 2024-10-02 06:47:00

在完整框架下的C#中,可以直接封送数组。请参阅数组的默认封送处理。我不知道 Compact Framework 有什么限制。

In C# under the full framework, you can marshal the array directly. See Default Marshaling for Arrays. I don't know what the limitations are on the Compact Framework.

眼泪都笑了 2024-10-02 06:46:59

该结构具有固定的尺寸。传递数组没有意义,只需传递结构即可:

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

您确实存在内存管理问题。谁拥有指针?


好的,该结构实际​​上是可变大小的,并且指针指向数组。你需要另一种方法。只需预先分配一块非托管内存,而不是让 P/Invoke 编组器将数据复制到托管数组中。这实际上是一个硬要求,因为垃圾收集器可以移动数组,从而使指针无效。调用 Marshal.CoTaskMemAlloc() 来保留内存,稍后您必须释放它。并将函数的第一个参数更改为 IntPtr (而不是 out)。

您会发现编组结构也变得更加容易,无需固定内存。完成后不要忘记 Marshal.FreeCoTaskMem() 。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文