微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

编组可以采用多个结构的空 void* 参数并在 C#

如何解决编组可以采用多个结构的空 void* 参数并在 C#

我想用一个空的 void* 参数调用一个 C 函数,并在 C# 中检索它以打印结构值。

在这个例子中:

  1. C 代码会将两个结构体中的一个随机分配给 void 参数。
  2. C 代码返回值必须是 int。
  3. 可以修改 C 代码结构

如何在 C# 中检索和打印 C 结构体的内容

C

#include <time.h>
#include <stdlib.h>

void PrintKdesc(interTICKeyDescription* kdescr)
{
    kdescr->nItems++;
    printf("nItems = %d\n",kdescr->nItems);
}

void PrintKevent(interTICEvent* kevent)
{
    kevent->nbr++;
    printf("nbr = %d\n",kevent->nbr);
}

EXPORT int VoidPtrTest(void* test)
{
    interTICKeyDescription kdesc = { 1,0x250021,42 };
    interTICEvent kevent = { 2,8 };

    srand(time(NULL));
    int r = rand() % 2;
    if (r == 1)
    {
        test = &kdesc;
        PrintKdesc(test);
    }
    else
    {
        test = &kevent;
        PrintKevent(test);
    }
    return (0);
}
typedef struct {
    int          id;
    unsigned int networkId;
    unsigned int implVersion;
    int          nItems;
} interTICKeyDescription;

typedef struct {
    int          id;
    int          nbr;
} interTICEvent;

C#

[StructLayout(LayoutKind.Sequential)]
public struct InterTICKeyDescription
{
    public int id;
    public UInt32 networkId;
    public UInt32 implVersion;
    public int nItems;
}

[StructLayout(LayoutKind.Sequential)]
public struct InterTICEvent
{
    public int id;
    public int nbr;
}
[DllImport("SandBox.dll",CallingConvention = CallingConvention.Cdecl,CharSet = CharSet.Ansi)]
extern static int VoidPtrTest(IntPtr test);

我的尝试

        static void Main()
        {
            InterTICKeyDescription kdesc = new InterTICKeyDescription();
            InterTICEvent kevent = new InterTICEvent();
            IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(kdesc));

            VoidPtrTest(ptr);

            int id = Marshal.ReadInt32(ptr,0);
            if (id == 1)
            {
                kdesc = (InterTICKeyDescription)Marshal.PtrToStructure(ptr,typeof(InterTICKeyDescription));
                Console.WriteLine("Id 1: " + kdesc.nItems);
            }
            else
            {
                kevent = (InterTICEvent)Marshal.PtrToStructure(ptr,typeof(InterTICEvent));
                Console.WriteLine("Id 2: " + kevent.nbr);
            }
            Marshal.FreeHGlobal(ptr);
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。