Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing a C# class object in and out of a C++ DLL class
    primarykey
    data
    text
    <p>I've been working on a prototype code application that runs in C# and uses classes and functions from older C++ code (in the form of an imported DLL). The code requirement is to pass in a class object to the unmanaged C++ DLL (from C#) and have it be stored/modified for retrieval later by the C# application. Here's the code I have so far...</p> <p>Simple C++ DLL Class:</p> <pre><code>class CClass : public CObject { public: int intTest1 }; </code></pre> <p>C++ DLL Functions:</p> <pre><code>CClass *Holder = new CClass; extern "C" { // obj always comes in with a 0 value. __declspec(dllexport) void SetDLLObj(CClass* obj) { Holder = obj; } // obj should leave with value of Holder (from SetDLLObj). __declspec(dllexport) void GetDLLObj(__out CClass* &amp;obj) { obj = Holder; } } </code></pre> <p>C# Class and Wrapper:</p> <pre><code>[StructureLayout(LayoutKind.Sequential)] public class CSObject { public int intTest2; } class LibWrapper { [DLLImport("CPPDLL.dll")] public static extern void SetDLLObj([MarshalAs(UnmanagedType.LPStruct)] CSObject csObj); public static extern void GetDLLObj([MarshalAs(UnmanagedType.LPStruct)] ref CSObject csObj); } </code></pre> <p>C# Function Call to DLL:</p> <pre><code>class TestCall { public static void CallDLL() { ... CSObject objIn = new CSObject(); objIn.intTest2 = 1234; // Just so it contains something. LibWrapper.SetDLLObj(objIn); CSObject objOut = new CSObject(); LibWrapper.GetDLLObj(ref objOut); MessageBox.Show(objOut.intTest2.ToString()); // This only outputs "0". ... } } </code></pre> <p>Nothing but junk values appear to be available within the DLL (coming from the passed in C# object). I believe I am missing something with the class marshalling or a memory/pointer issue. What am I missing?</p> <p>Edit: I changed the above code to reflect changes to the method/function definitions, in C#/C++, suggested by Bond. The value (1234) being passed in is retrieved by the C# code correctly now. This has exposed another issue in the C++ DLL. The 1234 value is not available to the C++ code. Instead the object has a value of 0 inside the DLL. I would like to use predefined C++ functions to edit the object from within the DLL. Any more help is greatly appreciated. Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload