How you use technique (described) to work with C s

2019-02-27 04:45发布

问题:

How you use technique described here to work with C structures from .Net?

Ofcourse I need a code example - on 3 parts: C declaring parts, C++ wrapping around C and C# acsessing.

So what I wonder Is

C structture A has as one of its params structure B which consists of at least 2 types one of which is pointer to some variable C which should be declared.

We whant to have access from C# .Net to all A and B structures and its params and that variable C.

How to do such thing?

回答1:

Suppose these are the C structs in a file named structs.h

struct StructB
{
    int bMember1;
    int bMember2;
    int* bMember3;
};

struct StructA
{
    struct StructB aMember1;
};

In a new VC++ DLL project, enable Common Language RunTime Support (Old Syntax) and make sure C++ Exceptions are disabled. Build this for release target.

extern "C"
{
    #include "structs.h"
}

namespace Wrapper
{
    public __gc class NewStructB
    {
        private:
            StructB b;

        public:
            NewStructB()
            {
            }

            ~NewStructB()
            {
            }

            int getBMember1()
            {
                return b.bMember1;
            }

            void setBMember1(int value)
            {
                b.bMember1 = value;
            }

            int getBMember2()
            {
                return b.bMember2;
            }

            void setBMember2(int value)
            {
                b.bMember2 = value;
            }

            int* getBMember3()
            {
                return b.bMember3;
            }

            void setBMember3(int* value)
            {
                b.bMember3 = value;
            }
    };

    public __gc class NewStructA
    {
        public:
            NewStructB* b;

            NewStructA()
            {
                b = new NewStructB();
            }

            ~NewStructA()
            {
                delete b;
            }

            void ShowInfo()
            {
                System::Console::WriteLine(b->getBMember1().ToString());
                System::Console::WriteLine(b->getBMember2().ToString());
                System::Console::WriteLine((*b->getBMember3()).ToString());
            }
    };
};

Then create a new C# Console Application and reference the .dll file we just built. In Project Properties > Build, check "Allow unsafe code".

static void Main(string[] args)
{
    int toBePointed = 12345;

    Wrapper.NewStructA a = new Wrapper.NewStructA();

    a.b.setBMember1(10);
    a.b.setBMember2(20);

    unsafe
    {
        a.b.setBMember3(&toBePointed);
    }

    a.ShowInfo();

    Console.ReadKey();
}

As you can see, the original StructA is in a way eliminated!! And I'm not aware of any other way to access C structure members directly from C# due to access issues.



标签: c# .net c++ c clr