Skip to content

Code Quality: Added a static method to the PCWSTR struct that allows constructing from a string #17135

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed

Conversation

Lamparter
Copy link
Contributor

Resolved / Related Issues

Steps used to test these changes

  1. Built the app

This only introduces a new API that can be used in future PRs to make migrating from DllImport calls to CsWin32 generations easier, and does not have any effect over the app as it is.


This method makes it easier to pass in a PCWSTR struct to a P/Invoke method that might previously require a string input.
A lot of methods generated by CsWin32 that require unsafe will prefer a PCWSTR passed as an argument over a literal System.String however this method allows using a string value (via fixing the string in memory as a char*) for simplicity and so that code isn't reused.

e.g.:

unsafe void Example()
{
	HANDLE file = PInvoke.CreateFile(lpFileName: PCWSTR.FromString("example") ...);
}

Copy link
Member

@0x5bfa 0x5bfa left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can cause memory corruption and thats why CsWin32 doesn't provide something like this.

@Lamparter
Copy link
Contributor Author

This can cause memory corruption and thats why CsWin32 doesn't provide something like this.

@0x5bfa how do you propose that the PCWSTR struct is created from a managed string value then?

@Lamparter Lamparter closed this May 23, 2025
@Lamparter Lamparter deleted the cswin32/pcwstr-fromstring branch May 23, 2025 17:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants