封送指向类型数组的指针(托管 C# -> 非托管 C++)

发布于 2024-08-02 12:41:42 字数 395 浏览 2 评论 0原文

我在确定一种表示包含指向托管代码中的 Shorts 数组的指针的结构的方法时遇到了一些麻烦。该结构如下所示:

typedef struct
{
    short size;
    unsigned short** shortValues;
} UnmanagedStruct;

shortValues”的内存在非托管代码内部分配 - 因此,即使该字段只是指向短值数组的指针,也添加了额外的间接级别,以便调用者(托管代码)也可以看到分配的内存。 “size”字段表示数组中元素的数量。我如何在托管代码中表示这一点?

我以为我只需将它传递到 IntPtr 中,然后我无法弄清楚如何在非托管调用返回后访问这些值。

I am having some trouble settling on a way to represent a structure that contains a pointer to an array of shorts in my managed code. The struct looks like this:

typedef struct
{
    short size;
    unsigned short** shortValues;
} UnmanagedStruct;

memory for 'shortValues' is allocated inside unmanaged code -- therefore even though that field is simply a pointer to an array of short values, an additional level of indirection was added so that allocated memory is seen by the caller (managed code) too. The 'size' field represents the number of elements in the array. How do I represent this in managed code?

I thought I'd pass it in just an IntPtr, then I couldn't figure out how to access the values once the unmanaged call returns.

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

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

发布评论

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

评论(1

流星番茄 2024-08-09 12:41:42

不安全的代码可以吗?

public unsafe struct UnmanagedStruct
{
    public short size;
    public ushort** shortValues;
}

[DllImport("example.dll")]
public static extern void GetUnmanagedStruct(out UnmanagedStruct s);

如果您有一个指向 ushort 数组的指针:

public static unsafe void WriteValues()
{
    UnmanagedStruct s;
    GetUnmanagedStruct(out s);
    for (var i = 0; i < s.size; i++)
    {
        ushort x = (*s.shortValues)[i];
        Console.WriteLine(x);
    }
}

如果您有一个以 null 结尾的 ushort 数组:

public static unsafe void WriteValues()
{
    UnmanagedStruct s;
    GetUnmanagedStruct(out s);
    for (var i = 0; i < s.size; i++)
    {
        for (ushort* p = s.shortValues[i]; p != null; p++)
        {
            ushort x = *p;
            Console.WriteLine(x);
        }
    }
}

Is unsafe code ok?

public unsafe struct UnmanagedStruct
{
    public short size;
    public ushort** shortValues;
}

[DllImport("example.dll")]
public static extern void GetUnmanagedStruct(out UnmanagedStruct s);

If you have a pointer to an array of ushorts:

public static unsafe void WriteValues()
{
    UnmanagedStruct s;
    GetUnmanagedStruct(out s);
    for (var i = 0; i < s.size; i++)
    {
        ushort x = (*s.shortValues)[i];
        Console.WriteLine(x);
    }
}

If you have an array of null-terminated arrays of ushorts:

public static unsafe void WriteValues()
{
    UnmanagedStruct s;
    GetUnmanagedStruct(out s);
    for (var i = 0; i < s.size; i++)
    {
        for (ushort* p = s.shortValues[i]; p != null; p++)
        {
            ushort x = *p;
            Console.WriteLine(x);
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文