CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Mar 2005
    Location
    Detroit MI
    Posts
    80

    Transferring data between managed and unmanaged code

    Hi,

    ** Please move if I posted in the wrong forum - I wasn't sure where this belonged! **

    I'm looking for some advice... I would like to have a native C++ project read data from the process it is attached to, and feed that data to a C# project for analysis, and then pass a single return value back to the C++ class.

    Here's what I have so far:

    1/ A C# managed (obviously!) project (Code Library DLL)
    2/ A C++ managed project (DLL), with only one managed function 'FuncX', and the rest declared as unmanaged using the #pragma approach.

    I'm attaching the C++ DLL to a process and reading information from the process, and that all works fine.

    Because I will be writing a lot of app. code, I would like to use C#, which means I have to get the data read from my application using the C++ DLL into the C# project. I would like to just transfer the data by adding a reference of my C# project to the C++ project (hence me creating the C++ project as managed) and moving the data over in a struct or class (defined in the C# project). In the one managed function I am creating an instance of my C# managed 'data copier' class, copying the data to it (which compiles at least) and then looking to pass the data (within the populated class instance) and execution to the C# library, but it doesn't seem to work (all sorts of problems).

    Am I going down the right path here (and just need to persevere more)?

    Or, am I all wrong, and if so, what is the best way to accomplish this?

    Thanks for your help!
    Last edited by BigWinston; February 16th, 2010 at 09:20 PM.
    Regards,

    Big Winston

  2. #2
    Join Date
    Jul 2002
    Posts
    2,543

    Re: Transferring data between managed and unmanaged code

    Create C++/CLI class library and add new class to it. Define class methods which should do required work. What data you want to transfer, in what direction? For example, if you need to return byte array to C# client, you can define this function:
    Code:
    ref class MyClass
    {
        public:
            array<Byte>^ GetData();
    };
    In C# client project, add reference to C++/CLI project, and use it by the following way:
    Code:
    MyClass myClass = new MyClass();
    byte[] data = myClass.GetData();
    Internal implementation of GetData function may use unmanaged code, legacy C/C++ libraries and any else what you need. Data exchange protocol between C# client and C++/CLI library is defined by C++/CLI class methods.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured