通过引用将结构传递给非托管函数调用时收到SafeArrayTypeMismatchException

问题描述:

我的非托管函数签名如下:

My unmanaged function signature is as follows:

HRESULT extern WINAPI WFSStartUp ( DWORD dwVersionsRequired, LPWFSVERSION lpWFSVersion);


其中LPWFSVERSION
我是struct
的指针
我声明了以下struct


Where LPWFSVERSION
I is a pointer to struct

I declared the following struct

[StructLayout(LayoutKind.Sequential)]
 public class WFSVERSION
 {
     public int            wVersion;
     public int            wLowVersion;
     public int            wHighVersion;
     public char[]           szDescription;
     public char[]           szSystemStatus;
 };

[DllImport(@"C:\WINDOWS\system32\msxfs.dll")]


[return: MarshalAs(UnmanagedType.I4)]
public static extern int WFSStartUp(double dwVersionsRequired, [MarshalAs(UnmanagedType.LPStruct)] ref WFSVERSION rc);


在C#应用程序中调用该函数时,我得到
SafeArrayTypeMismatchException


When calling the function in my C# application I get
SafeArrayTypeMismatchException

WFSVERSION rc = new WFSVERSION();


rc.szDescription = new char[256];
rc.szSystemStatus = new char[256];

int result = WFSStartUp(130819, ref rc);



我知道该结构必须为IDispatch接口类型,所以我尝试了

请执行以下操作:



i understand that the struct needs to be of IDispatch interface type so I attempted

to do the following:

WFSVERSION rc = new WFSVERSION();
DispatchWrapper dispArray = new DispatchWrapper((object)rc);


但是,这给了我一个编译错误,说我的演员表不正确.请指教.我没办法了.


But then it gives me a compile error saying that my cast is incorrect. Please advise. I ran out of ideas.

是的,您的错误在
Yes, your error is in
WFSVERSION rc = new WFSVERSION();//incorrect
WFSVERSION rc();//correct
WFSVERSION *rc = new WFSVERSION(); //correct


语言混在一起?

这在C#中有效,但在C/C ++中无效

are you getting your languages mixed up?

This is valid in C# but invalid in C/C++

WFSVERSION rc = new WFSVERSION();
DispatchWrapper dispArray = new DispatchWrapper((object)rc); 



这在C/C ++螺母中有效,在C#中无效



This is valid in C/C++ nut invalid in C#

WFSVERSION *rc = new WFSVERSION();
DispatchWrapper *dispArray = new DispatchWrapper((object)rc); 



因此,您需要确保语法与互操作块中使用的代码相匹配.



So you need to make sure you match the syntax to the piece of code you are using in the interop pieces.


我已经指出了以下C#语句:
WFSVERSION rc =新的WFSVERSION();
DispatchWrapper dispArray = new DispatchWrapper((object)rc);

它会构建,但是在我的C#应用​​程序中调用该函数时会得到
SafeArrayTypeMismatchException
I''ve implementated the following C# statements as you pointed out:
WFSVERSION rc = new WFSVERSION();
DispatchWrapper dispArray = new DispatchWrapper((object)rc);

it builds but when calling the function in my C# application I get
SafeArrayTypeMismatchException