作者:手机用户2502923413 | 来源:互联网 | 2023-10-11 13:40
我在封送处理字符串上使用microsoft Docs示例。该代码不会崩溃,但不会在C#中返回预期的字符串。调用本机代码时,字符串未修改,因此我想知道此示例是否过时?
如果该示例不适用于其他人,是否还有另一种方法将C ++字符串数组编组为C#?
此处的C ++示例:
https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/as6wyhwt(v=vs.100)?redirectedfrom=MSDN
PINVOKELIB_API int TestArrayOfStrings( char* ppStrArray[],int count )
{
int result = 0;
STRSAFE_LPSTR temp;
size_t len;
const size_t alloc_size = sizeof(char) * 10;
for ( int i = 0; i {
len = 0;
StringCchLengthA( ppStrArray[i],STRSAFE_MAX_CCH,&len );
result += len;
temp = (STRSAFE_LPSTR)CoTaskMemAlloc( alloc_size );
StringCchCopyA( temp,alloc_size,(STRSAFE_lpcstr)"123456789" );
// CoTaskMemFree must be used instead of delete to free memory.
CoTaskMemFree( ppStrArray[i] );
ppStrArray[i] = (char *) temp;
}
return result;
}
此处的C#对应示例:
https://docs.microsoft.com/en-us/dotnet/framework/interop/marshaling-different-types-of-arrays
internal static class NativeMethods
{
[DllImport("..\\LIB\\PinvokeLib.dll",CallingCOnvention= CallingConvention.Cdecl)]
internal static extern int TestArrayOfstrings(
[In,Out] string[] stringArray,int size);
}
// string array ByVal
string[] strArray = { "one","two","three","four","five" };
Console.WriteLine("\n\nstring array before call:");
foreach (string s in strArray)
{
Console.Write(" " + s);
}
int lenSum = NativeMethods.TestArrayOfstrings(strArray,strArray.Length);
Console.WriteLine("\nSum of string lengths:" + lenSum);
Console.WriteLine("\nstring array after call:");
foreach (string s in strArray)
{
Console.Write(" " + s);
}