当前位置: 动力学知识库 > 问答 > 编程问答 >

Passing a Safearray of custom types from C++ to C#

问题描述:

how can one use a Safearray to pass an array of custom types (a class containing only properties) from C++ to C#? Is using the VT_RECORD type the right way to do it?

I am trying in the following way, but SafeArrayPutElement returns an error when trying to fill the safearray the reference to the array of classes gets to the managed code as a NULL.

I have something like the following in the managed world:

[ComVisible(true)]

public interface IStatistics

{

double Mean { get; set; }

double StdDev { get; set; }

}

[Serializable]

[ComVisible(true)]

public class Statistics : IStatistics

{

public Mean { get; set; }

public double StdDev { get; set; }

}

Unmanaged world:

HRESULT hr = CoInitialize(NULL);

...

SAFEARRAY *pEquationsStatistics;

// common dimensions for all arrays

SAFEARRAYBOUND dimensions[1];

dimensions[0].cElements = 2;

dimensions[0].lLbound = 0;

pEquationsStatistics = SafeArrayCreate(VT_RECORD, 1, dimensions);

...

for (long i = 0; i < dimensions[0].cElements; i++)

{

long indices[1];

indices[0] = 0;

...

// Equation statistics

IStatisticsPtr pIStatistics(__uuidof(Statistics));

pIStatistics->PutMean(1.0); // so far so good

result = SafeArrayPutElement(pEquationsStatistics, indices, pIStatistics);

...

indices[0]++;

}

Please note that the I am able use the SafeArray to pass other arrays of BSTR with no problems between the two applications. So this is something peculiar to passing a structure.

Stefano

网友答案:

I'm not really sure if I understand your question right, but maybe you need VT_DISPATCH? I think if you want it to work with VT_RECORD, then your struct should actually be a struct (not a class) and also needs the [StructLayout(LayoutKind.Sequential)] attribute.

Edit: Can it be that the error you first got was DISP_E_BADINDEX? What exactly is indices in your code? What does it contain? (You know that the signature of SafeArrayPutElement requires it to be a pointer, right?)

分享给朋友:
您可能感兴趣的文章:
随机阅读: