title: Setting variables in C++ through C# structure
body: <p>I have a solution with 3 projects. A C# WinForms project which depends on second project which is a C++ DLL. The C++ DLL depends on the third project which is a static library. The static library is C code with C++ classes. The DLL acts as an interop between the C code and C# code.</p>
  
  <p>I need to set the variables used by the static library through C# structure.</p>
  
  <p>I do not have experience in C++/CLI (I have started reading. Examples found on the web do not make sense to me as of now)</p>
  
  <p>So far, I have created a structure in C#. I created a initialized unmanaged memory to hold this struct: </p>
  
  <pre><code>IntPtr ptData = Marshal.AllocHGlobal(Marshal.SizeOf(objMyClass.data));//data is the structure I am initializing in the constructor of MyClass
  Marshal.StructureToPtr(objPythonInterop.data, ptData, false);
  objCPPClass.UpdateData(ptData);//objCPPClass is object to class in DLL. libClass is the object of class in static library
  </code></pre>
  
  <p>This is my structure in C#:</p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential)]
  public struct Data
  {
      members here..
  }
  </code></pre>
  
  <p>In the DLL, this is the <code>UpdateData</code> function:</p>
  
  <p>Header:</p>
  
  <pre><code>void UpdateData(IntPtr ptrData);
  </code></pre>
  
  <p>Source:</p>
  
  <pre><code>void CPPClass::UpdateData(IntPtr ptrData)
  {
      m_lib-&gt;UpdateDataInLib(ptrData);// m_lib is object to class in static library
  }
  </code></pre>
  
  <p><code>UpdateDataInLib</code> is a function in the Class in Static library. How do I use the ptrData in this function and update the variables? I have a structure in the static library similar to the structure defined in my C# code. How do I cast the ptr to this structure and access the members?</p>
  
  <p>I have a structure in my C++ static library which contains equivalent members of the structure in C#:</p>
  
  <pre><code>extern "C"  __declspec(dllexport) typedef struct Data
  {
      members here..
  }Data, *pData;
  </code></pre>
  
  <p>I need help.</p>