如何修复ArrayList兼容UNICODE_STRING时的结构体比较语法错误?
Hey there! Let's get that C2088 error sorted out. The problem is pretty straightforward once you break down why it's happening.
Why You're Getting the Error
In C, you can't use the == operator directly on structs like UNICODE_STRING—the compiler doesn't know how to automatically compare all the members of a composite type. Your original code worked with an int because that's a primitive value, but UNICODE_STRING has multiple fields (Length, MaximumLength, Buffer), so the direct == check throws that "illegal use of '==' on struct" error.
Solution: Use a Custom Comparison Function
You need to replace the direct == check with a function that properly compares the two UNICODE_STRING structs. Here are two reliable approaches depending on your environment:
Option 1: Use Windows' Built-in Function (Kernel/User Mode)
Since you're working with UNICODE_STRING (a Windows-specific type), you can use the RtlEqualUnicodeString function from the Windows API. It safely compares two UNICODE_STRING instances by checking lengths first, then verifying buffer contents.
First, ensure you have the right headers (kernel mode uses ntddk.h; user mode may need winternl.h). Then update your indexOf function:
int indexOf(ArrayList* list, UNICODE_STRING data) { for (int index = 0; index < list->size; index++) { // Replace == with the built-in comparison function if (RtlEqualUnicodeString(&data, &list->elements[index].data, TRUE)) { // TRUE = case-insensitive; use FALSE for case-sensitive comparison return index; } } return -1; }
Option 2: Implement Your Own Comparison Function
If you can't rely on the Windows built-in function, write a custom helper to compare the structs manually:
BOOL AreUnicodeStringsEqual(const UNICODE_STRING* str1, const UNICODE_STRING* str2) { // First check if lengths match (bytes, not characters) if (str1->Length != str2->Length) { return FALSE; } // Empty strings are equal if (str1->Length == 0) { return TRUE; } // Compare the actual buffer content return memcmp(str1->Buffer, str2->Buffer, str1->Length) == 0; } // Update indexOf to use your custom function int indexOf(ArrayList* list, UNICODE_STRING data) { for (int index = 0; index < list->size; index++) { if (AreUnicodeStringsEqual(&data, &list->elements[index].data)) { return index; } } return -1; }
Quick Tips
- Always pass pointers to
UNICODE_STRINGstructs to comparison functions (using&)—this is more efficient and aligns with standard string comparison patterns. - For case-insensitive checks in a custom function, swap
memcmpwithwcsnicmp(just remember to convert the byte length to character count first).
内容的提问来源于stack exchange,提问作者user9628077

