编组可以采用多个结构的空 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 (将#修改为@)