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&#d;字符串传递的,我需要在C / C ++端释放它,还是CLR会为我处理它?如果它被清理干净,我是否正确传递了它?我可以将它作为普通的C#字符串传递而不是[MarshalAsAttribute(UnmanagedType.LPWStr)]
吗?谢谢!
答案 0 :(得分:1)
C#会将C#字符串的副本复制到非托管内存中,传递指针并在函数调用完成后删除字符串