kekyo / IL2C

IL2C - A translator for ECMA-335 CIL/MSIL to C language.
Apache License 2.0
403 stars 36 forks source link

Suggest: Capable native pointer marshaling on IL2C interoperability. #67

Open kekyo opened 5 years ago

kekyo commented 5 years ago

For example, C# with P/Invoke way:

struct Foo
{
}

struct Bar
{
   // Foo* field1;    // C# and P/Invoke can't handle native pointer on the structure.
   IntPtr field1;      // And formal way is manually marshaling...
}

If IL2C/Invoke can handle directly it, very easier in the situation. We discussed how to implement this way for first inspirations:

[NativeType(...)]
struct Foo
{
}

[NativeType(...)]
struct Bar
{
   [NativePointer(...)]
   Foo field1;
}

Foo foo = new Foo();
Bar bar = new Bar();
foo.field1 = bar;

In Roslyn, the code fragment understands the bar will copy instance into foo.field1. But IL2C will wirte the bar variable is the pointer:

// Bar is value type.
Bar bar = ...
foo->field1 = &bar;    // store the bar's pointer (stfld opcode)

We have to think more deep things:

@chameleonhead Thanks discussed and suggested at Center CLR Try development meetup No.6.

chameleonhead commented 5 years ago

I wanted to write code like ...

        [NativeValue("winsock2.h", SymbolName = "WSADESCRIPTION_LEN")]
        static readonly int WSADESCRIPTION_LEN = 256;

        [NativeValue("winsock2.h", SymbolName = "WSASYS_STATUS_LEN")]
        static readonly int WSASYS_STATUS_LEN = 128;

        [NativeType("winsock2.h", SymbolName = "WORD")]
        struct WORD
        {
            public byte bLow;
            public byte bHigh;
        }

        [NativeType("winsock2.h", SymbolName = "WSADATA")]
        struct WSADATA
        {
            WORD wVersion;
            WORD wHighVersion;
            byte[] szDescription;
            byte szSystemStatus;
            ushort iMaxSockets;
            ushort iMaxUdpDg;
            IntPtr lpVendorInfo;
        };

        [NativeMethod("winsock2.h", SymbolName = "socket")]
        static extern WSADATA WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData);

But I could not know how to write LPWSADATA (which is WSADATA*).

Thank you for taking up.

kekyo commented 5 years ago

Memoized for me: the ref keyword in C#7, can we handle the field pointer type natural expressions?