在这个例子中,C指针如何与C#相关联?

时间:2016-11-01 10:19:47

标签: c# c

我目前正在尝试将一个库从C语言移植到C#,到目前为止大部分都已顺利进行,但是当我从C语言转换结构指针时遇到了障碍。

以下是我要转换的C代码:

//Queue.c File
struct queue
{
    struct queue* next;
    void* e;
};

struct queue* create_queue_node(void* element)
{
    struct queue* tmp = malloc_node();
    tmp->e = element;
    return tmp;
}

void append_queue_node(struct queue* node, struct queue* after) // adds node next to after
{
    node->next = after->next;
    after->next = node;
}


//Allocator.c File
#define QUEUE_CHUNK 65536
#define MOVE_CHUNK 65536

struct move* alloc_moves = 0; // allocated moves
int last_move = MOVE_CHUNK;
struct move freed_moves;

struct queue* alloc_nodes = 0; // allocated nodes 
int last_node = QUEUE_CHUNK;
struct queue freed_nodes;

void inicialize_allocator()
{
    freed_moves.parent = 0;
    freed_nodes.next = 0;
}

struct queue* malloc_node()
{
    if (last_node < QUEUE_CHUNK)
        return &alloc_nodes[last_node++];
    else
    {
        alloc_nodes = malloc(sizeof(struct queue)*QUEUE_CHUNK);
        last_node = 1;
        return alloc_nodes;
    }
}

现在我明白C#将一个Class作为引用类型,因此C中的(queue* node)与C#中的(Queue node)相同(如果我理解正确的话)。所以这是我到目前为止的C#代码:

//Queue.cs File
public class Queue
    {
        public Queue next;
        public IntPtr e;

        public Queue createQueueNode(IntPtr element)
        {
            Queue tmp = mallocNode();
            tmp.e = element;
            return tmp;
        }

        public void appendQueueNode(Queue node, Queue after)
        {
            node.next = after.next;
            after.next = node;
        }

        public Queue removeQueueNode(Queue before)
        {
            Queue tmp = before.next;
            before.next = before.next.next;
            return tmp;
        }

        public bool isQueueEmpty(Queue head)
        {
            return head.next == null;
        }
    }

//Allocator.cs File
public static class Allocator
{
    public static Move allocMoves = null;
    public static int lastMove = Global.MOVECHUNK;
    public static Move freedMoves = null;

    public static Queue allocNodes = null;
    public static int lastNode = Global.QUEUECHUNK;
    public static Queue freedNodes = null;

    public static void initializeAllocator()
    {
        freedMoves.parent = null;
        freedNodes.next = null;
    }

    public static Queue mallocNode()
    {
        if(lastNode < Global.QUEUECHUNK)
        {
            return //?
        }
        else
        {
            allocNodes = new //?
            lastNode = 1;
            return allocNodes;
        }
    }
}

我不确定如何分配allocNodes变量,或者它在返回行上的用法。如何在C#中实现这样的东西?

0 个答案:

没有答案