After downloading and installing the Silverlight 5 RC Tools for VS 2010 SP1, I created a simple Silverlight 5 application project. Discouragingly, the Unsafe checkbox in the project settings is still disabled:
But at least the checkbox is there... Maybe I can manually edit the project file. In a regular C# project, unsafe support is indicated within each configuration/platform PropertyGroup using the following tag:
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
Next, let's see if I can add some unsafe code and build it. First, I create a button with the instructive text "Click me!". I add the following event handler for the button Click event:
unsafe private void UnsafeTestButton_Click(
object sender, RoutedEventArgs e)
{
int i = 5;
SquarePtrParam(&i);
UnsafeTestButton.Content = i;
}
The event handler in turn calls a simple unsafe method that dereferences an integer pointer and squares it:
unsafe static void SquarePtrParam(int* p)
{
*p *= *p;
}
After calling the SquarePtrParam method, the click event handler should update the button content to the value of the squared integer. (If the code looks familiar I have copied it from MSDN:s C# reference section on unsafe.)
When I now build this "unsafe" Silverlight application, I get the encouraging prompt "Rebuild All succeeeded"!
Next question is, can the "unsafe" Silverlight application also be executed? It turns out that when I run it in-browser and click the button, I encounter a VerificationException, "Operation could destabilize the runtime", regardless of whether I run in normal or elevated trust. When I run out-of-browser, I get the same exception when running in normal trust, but when running out-of-browser and elevated trust, I can successfully go from here:
to here:
So the conclusion is that Silverlight 5 RC does provide hidden-away support for unsafe code. At this point it only seems to be executable out-of-browser in elevated trust. It will be interesting to see to what extent the unsafe support will be exposed in the official Silverlight 5 release.
Sidenote: I was also able to build the "unsafe" project with Silverlight 4. However, in this case I encountered the VerificationException in out-of-browser elevated-trust mode as well.
hello,
ReplyDeleteI need your help.
I couldn't understand where should I put true
tags in Silverlight Project.
There is no config file In my Project.
My solution has two projects,c# and silverlight.
Thanks a lot! This is very helpful. :)
ReplyDeleteFor anyone who doesn't know where put the line: AllowUnsafeBlocks>true AllowUnsafeBlocks
Right click on Properties file -> open containing folder:
Right click on Highlighting file -> Edit (Notepad) and Paste the line in the first PropertyGroup
Good luck!