Note that there are some explanatory texts on larger screens.

plurals
  1. POSafeArrayPutElement method throws System.AccessViolationException
    primarykey
    data
    text
    <p>I am trying to pass an array of ints from C# to C++/CLI. Here's my code:</p> <pre><code>// SafeArrayTesting_PlusPlus.cpp #include "stdafx.h" #include &lt;comdef.h&gt; using namespace System; namespace SafeArrayTesting_PlusPlus { public ref class MyCppClass { public: MyCppClass(); ~MyCppClass(); void SetMyInts(array&lt;int&gt;^ myInts); }; MyCppClass::MyCppClass(){} MyCppClass::~MyCppClass(){} void MyCppClass::SetMyInts(array&lt;int&gt;^ myInts) { // Create safearray SAFEARRAY *safeArrayPointer; SAFEARRAYBOUND arrayDim[1]; // one dimensional array arrayDim[0].lLbound= 0; arrayDim[0].cElements= myInts-&gt;Length; safeArrayPointer = SafeArrayCreate(VT_UNKNOWN,1,arrayDim); // copy ints to safearray for (long lo= 0; lo &lt; myInts-&gt;Length; lo++) { cli::pin_ptr&lt;int&gt; pinnedIntPointer = &amp;(myInts[lo]); SafeArrayPutElement( safeArrayPointer, &amp;lo, static_cast&lt;void*&gt; (pinnedIntPointer)); // line XX } // do something with the safearray here } } // SafeArrayTesting_Main.cs using SafeArrayTesting_PlusPlus; namespace SafeArrayTesting_Main { class SafeArrayTesting_Main { static void Main() { var myCppClass = new MyCppClass(); myCppClass.SetMyInts(new[]{42}); } } } </code></pre> <p>When I run this, line XX throws the following exception:</p> <blockquote> <p>System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.</p> </blockquote> <p>I have a feeling that I'm doing something basically wrong with the <code>SafeArrayPutElement</code> method. Can you spot the error?</p> <p>(By the way, I have asked a more complex variation of this question at <a href="https://stackoverflow.com/questions/3464901/">Passing an array of interfaces from C# to C++/CLI</a> . I think the difference is big enough to warrant two separate questions.)</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.
 

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