本文介绍了通过 Pinvoke 传递 C# 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C# 端:
[DllImport(@"FileGuidUtils.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern long getReparseType([MarshalAsAttribute(UnmanagedType.LPWStr)] string linkPath);
C/C++ 端:
__declspec(dllexport) ReparseType getReparseType(WCHAR *linkPath) {
HANDLE hFile = CreateFile(linkPath, GENERIC_ALL, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
CloseHandle(hFile);
return NEITHER;
}
REPARSE_DATA_BUFFER *reparseDataBuffer = (REPARSE_DATA_BUFFER *)malloc(MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
DWORD dwRetLen = 0;
BOOL bRet = DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, reparseDataBuffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &dwRetLen, NULL);
if (bRet == FALSE)
{
free(reparseDataBuffer);
CloseHandle(hFile);
return NEITHER;
}
ULONG reparseType = reparseDataBuffer->ReparseTag;
free(reparseDataBuffer);
CloseHandle(hFile);
if (reparseType == IO_REPARSE_TAG_SYMLINK) {
return SYMLINK;
}
else if (reparseType == IO_REPARSE_TAG_MOUNT_POINT) {
return JUNCTION;
}
return NEITHER;
}
linkPath 是如何传递的?它是作为 malloc 字符串传递的,我需要在 C/C++ 端释放它还是 CLR 会为我处理它?如果它被清理干净,我是否正确传递了它?我可以将它作为没有 [MarshalAsAttribute(UnmanagedType.LPWStr)]
的普通 C# 字符串传递吗?谢谢!
How is linkPath passed? Is it passed as a malloc'd string and I need to free it up on the C/C++ side or will the CLR take care of it for me? If it is getting cleaned up, am I passing it correctly? Could I just pass it as an ordinary C# string without the [MarshalAsAttribute(UnmanagedType.LPWStr)]
? Thanks!
推荐答案
C# 会为你复制一个 C# 字符串到非托管内存中,传递一个指向它的指针并在函数调用完成后删除该字符串
C# will make a copy of the C# string for you into unmanaged memory , pass a pointer to it and delete the string once the function call is finished
这篇关于通过 Pinvoke 传递 C# 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!