简体   繁体   中英

Passing an array from managed code to unmanaged C++ ActiveX component

In an earlier post Passing pointer from managed C++/CLI to ActiveX C++ component I've asked about the correct means to pass an array (whether managed or unmanaged array) to an activeX component created in native C++. The activeX method has the following signature:

short Component::CopyToBuffer(short FAR* ptr) {}

when the activeX is imported to be used in C++/CLI

the method signature is displayed as

short Component::CopyToBuffer(short% ptr) {}

when imported in C# it is displayed as

short Component::CopyToBuffer(ref short ptr) {}

However, I was not able to pass the array correctly.

whether native array: short* shortsArray = new short[500];

neither a managed array: array<short>^ shortsArray = gcnew array<short>(500);

users ildjarn and Hans Passant suggested that I need to edit the interop assembly file to change the exported method signature to something like Component::(int16[] ptr) which I did and successfully compiled the project but ran into other kind of problems (type mismatch or something).

So now I've made a sample project that reproduces the problemnSolution
The solution contains:

  • A project for the ActiveX component with one method CopyToBuffer found in SomeCompCtl.h
  • A test project in C++/CLI. with a single form that has the activeX added to it and a button calls the method with an array of given values.
  • Another test project in C# that does the same thing

To run the project: - Simply compile SomeComp to generate Somecomp.ocx which contains the ActiveX. - regsrv32 the ActiveX control

Please note that I don't access to the ActiveX code (I've had access to one version of code but I cannot presume that the developers will continue to provide me with updated versions of code) so any solutions shouldn't depend on changing the ActiveX interfaces or code. I normally only have the ocx file with its tlb file.

With the signature as CopyToBuffer(short% ptr) , how did you call it? If you did CopyToBuffer(myArray[0]) or CopyToBuffer(&myArray[0]) , that could fail because the garbage collector could move the array on you. Try this:

pin_ptr<short> pinned = &myArray[0];
component->CopyToBuffer(pinned);

If that doesn't work, try editing the interop assembly file again, change the signature to CopyToBuffer(IntPtr ptr) . Since it's more explicit about the fact that the parameter is a simple pointer, perhaps that will work better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM