none
P/INVOKE compatibility in c# RRS feed

  • Question

  • Hello,

    I am using visual  c++ 2008 Express Edition and visual c# 2008 express edition.

    I have a C DLL which i have imported in my C# application.

    This C DLL contains  some data structures and variables defined for that data structures.

    e.g.

    typedef struct

    {

       int slotNumber;

       int status;

    }SLOTINFO;

    SLOTINFO[] slotObj;

    I want to make available slotObj[] in my c# code.

    For this I created a similar structure in c#, I created one variable of this structure.

    now I want to assign C structure's variable i.e slotObj to the same structure's variable of c#.

    Is there any matter with P/INVOKE compatibility to do this?

    What is the best way to do this?

    Please reply ASAP.

    Thanks & Regards..

    Wednesday, March 24, 2010 9:44 AM

Answers

  • You have several ways to do it:

    1) The unmanaged array have to be returned from C++ code somehow -> so put in P/Invoked function declaration array of managed structs (pass C# array of structs already to C++ function) - ByRef or ByVal (it depends)

    2) There's special command to convert managed struct to unamanged. Marshall.PtrToStructure and Marshall.StructToPtr - it even can work on array of struct you just must define size of struct (in attributes)

    There's other non trivial ways to pass array of structures from managed to unmanaged code but I would start from those two first


    C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off (c) — Bjarne Stroustrup [http://www2.research.att.com/~bs/bs_faq.html#really-say-that]
    Wednesday, March 24, 2010 12:50 PM

All replies

  • You have several ways to do it:

    1) The unmanaged array have to be returned from C++ code somehow -> so put in P/Invoked function declaration array of managed structs (pass C# array of structs already to C++ function) - ByRef or ByVal (it depends)

    2) There's special command to convert managed struct to unamanged. Marshall.PtrToStructure and Marshall.StructToPtr - it even can work on array of struct you just must define size of struct (in attributes)

    There's other non trivial ways to pass array of structures from managed to unmanaged code but I would start from those two first


    C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off (c) — Bjarne Stroustrup [http://www2.research.att.com/~bs/bs_faq.html#really-say-that]
    Wednesday, March 24, 2010 12:50 PM
  • PInvoke Interop Assistant tool may help you with this.

    http://clrinterop.codeplex.com/releases/view/14120

     

    Thursday, March 25, 2010 3:13 PM
  • Thank you.
    Friday, March 26, 2010 10:56 AM