CA1417: Do not use OutAttribute
on string parameters for P/Invokes
Property | Value |
---|---|
Rule ID | CA1417 |
Title | Do not use OutAttribute on string parameters for P/Invokes |
Category | Interoperability |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 8 | As warning |
Cause
A P/Invoke string parameter is passed by value and marked with OutAttribute.
Rule description
The .NET runtime automatically performs string interning. If an interned string marked with OutAttribute is passed by value to a P/Invoke, the runtime can be destabilized.
How to fix violations
If marshalling of modified string data back to the caller is required, pass the string by reference instead. Otherwise, the OutAttribute can be removed without any other changes.
// Violation
[DllImport("MyLibrary")]
private static extern void Foo([Out] string s);
// Fixed: passed by reference
[DllImport("MyLibrary")]
private static extern void Foo(out string s);
// Fixed: marshalling data back to caller is not required
[DllImport("MyLibrary")]
private static extern void Foo(string s);
When to suppress warnings
It is not safe to suppress a warning from this rule.
See also
Cộng tác với chúng tôi trên GitHub
Bạn có thể tìm thấy nguồn cho nội dung này trên GitHub, nơi bạn cũng có thể tạo và xem lại các vấn đề và yêu cầu kéo. Để biết thêm thông tin, hãy xem hướng dẫn dành cho người đóng góp của chúng tôi.
Phản hồi
https://aka.ms/ContentUserFeedback.
Sắp ra mắt: Trong năm 2024, chúng tôi sẽ dần gỡ bỏ Sự cố với GitHub dưới dạng cơ chế phản hồi cho nội dung và thay thế bằng hệ thống phản hồi mới. Để biết thêm thông tin, hãy xem:Gửi và xem ý kiến phản hồi dành cho