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

别等时光非礼了梦想. 提交于 2019-12-11 07:21:18

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/6217293/passing-an-array-from-managed-code-to-unmanaged-c-activex-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!