开发者

How to create unmanaged nested fixed length structure in C# that can be accessed using pointers

We have a lot of legacy code written in C/C++ that maintains data in shared memory structures. In the C/C++ implementations, for a lot of functions, we get a pointer to the shared memory address then cast that pointer to the type of structure that is contained in that shared memory.

I have a need to "port" the same interface to C#. The requirements are that we cannot change any of t开发者_开发知识库he C/C++ implementation and the interfaces are used to access the data in near real time (so performance is an issue). A lot of the data structures contain nested structures of other user defined structures. The primary way to access the data is to get a point to the structure then directly access the desired elements.

My problem is how to create equivalent data structures in C# that are completely unmanaged and can be used in C# by pointers. In C#, nested structures can be created using the fixed attribute, but that attribute only supports primitive data types, you cant use the fixed keyword with user defined types. Most of the examples on the Web use marshaling to access the data elements, but the declaration style in those examples causes the data structure to be managed so it cant be used as pointers.

The following is a simple example of the C/C++ implementation that needs ported to C#.

Does anyone have a method for converting this to a C# implementation that creates a purely unmanaged data structure that can be access as unsafe with pointers?

// Structures.cpp : Defines the entry point for the console application.
//

'#include "StdAfx.h"

typedef struct inner_struct
{
    int a;
    float b;
    char text[16];
} InnerStruct;

'#define NUMELEMENTS 20

typedef struct outer_struct
{
    int flag;
    int num;
    InnerStruct data[NUMELEMENTS];
} OuterStruct;

void *fSharedMemory();

int _tmain(int argc, _TCHAR* argv[])
{
    int a;

    OuterStruct *data = NULL;

    data = (OuterStruct *)fSharedMemory();

    while (true)
    {
        if (data->flag)
            for (int i=0; i<data->num; i++) {
                a = data->data[i].a;
            }

        Sleep(100);
    }

    return 0;
}

I feel like I am missing something here. Given enough time and money we would rewrite all of the implementation as managed code, but I have to believe I am not the only one who has to interface with legacy code.


You can use PInvoke/Marshalling to do what you need

http://msdn.microsoft.com/en-us/library/aa288468%28VS.71%29.aspx

There are examples on that site, it will let you integrate in DLL's and C/C++ structures into C#.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜