int __stdcall getProps( /* [ in ] */ void * context,
/* [ in ] */ const UINT32 index,
/* [ in ] */ WCHAR * const pwszFilterPath,
/* [ in, out ]*/ UINT32 * const pFilterPathSizeInCch,
/* [ in ]*/ WCHAR * const pwszFilterName,
/* [ in, out ] */ UINT32 * const pFilterNameSizeInCch );
对于签名以上的C函数,此C#签名正确吗?
[DllImport("myLib.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
public static extern int getProps( IntPtr context,
uint index,
[MarshalAs(UnmanagedType.LPWStr)]
out StringBuilder pwszFilterPath,
ref uint pFilterPathSizeInCch,
[MarshalAs(UnmanagedType.LPWStr)]
out StringBuilder pwszFilterName,
ref uint pFilterNameSizeInCch );
这里有问题,我不知道是什么(我不知道C#)。有时,当我开始使用它时,我会在StringBuilder变量中收到ANSI字符串,并且它们应包含UNICODE字符。
想法是调用此函数两次。首先将pwszFilterPath和pwszFilterName设置为NULL,以便检索所需的大小,然后为这两个缓冲区分配内存,然后在第二次调用中检索值。我知道如何在C / C ++中做到这一点,但在C#中却不知道。
您必须out
从StringBuilder
参数中删除关键字。将纯StringBuilder
参数编组为指向字符数组的指针。如果您希望接收本机代码NULL
,请传递C#null
。
[DllImport("myLib.dll", CharSet = CharSet.Unicode)]
public static extern int getProps(
IntPtr context,
uint index,
StringBuilder pwszFilterPath,
ref uint pFilterPathSizeInCch,
StringBuilder pwszFilterName,
ref uint pFilterNameSizeInCch
);
调用模式如下:
null
给StringBuilder
参数以找出缓冲区大小。StringBuilder
使用接收容量的构造函数重载分配实例。StringBuilder
实例再次调用该函数。也许像这样:
uint filterPathLength = 0;
uint filterNameLength
int retval = getProps(
context,
index,
null,
ref filterPathLength,
null,
ref filterNameLength
);
// check retval
StringBuilder filterPath = new StringBuilder(filterPathLength);
StringBuilder filterName = new StringBuilder(filterNameLength);
int retval = getProps(
context,
index,
filterPath,
ref filterPathLength,
filterName,
ref filterNameLength
);
// check retval
而且,您需要确保正确使用null终止符的长度约定。我无法判断您的函数是否返回包含空终止符的长度。
正如@Ben指出的那样,您的注释与文本描述不匹配。
/* [ in ] */ WCHAR * const pwszFilterPath
[in]应该表示数据正在流入函数中。在这种情况下,类型应为const WCHAR*
。但事实并非如此。这是一个out参数。因此,代码应显示为:
/* [ out ] */ WCHAR * const pwszFilterPath
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句