0

我想用一个空的 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, 0, 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);
        }
4

0 回答 0