How to run unsafe code in "visual studio code"?
Asked Answered
H

3

18

I am using Visual studio code and when I try to run an unsafe code it throws the following error ""message": Unsafe code may only appear if compiling with /unsafe"

and as in visual studio, it does not have option like project->properties.

Hintze answered 1/6, 2018 at 5:36 Comment(0)
A
26

unsafe (C# Compiler Options)

  1. To set this compiler option in the Visual Studio development environment Open the project's Properties page.

    1. Click the Build property page.

    2. Select the Allow Unsafe Code check box.

  2. To add this option in a csproj file Open the .csproj file for a project, and add the following elements:

XML

  <PropertyGroup>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  </PropertyGroup>

Usage

Method level

unsafe static void FastCopy(byte[] src, byte[] dst, int count)  
{  
    // Unsafe context: can use pointers here.  
}  

Inline Block

...

unsafe  
{  
    // Unsafe context: can use pointers here.  
}

Class Level

public unsafe class Blah {}
Actress answered 1/6, 2018 at 5:43 Comment(1)
Note that in the general case a Visual Studio Code C# project may not have a .csproj file. See code.visualstudio.com/Docs/languages/…Beery
H
12

In the .csproj file, just add

<AllowUnsafeBlocks>true</AllowUnsafeBlocks>

to any <PropertyGroup> block.

No need to add anything to task.json.

Hurryscurry answered 29/7, 2018 at 6:32 Comment(1)
Source: learn.microsoft.com/en-us/dotnet/csharp/language-reference/…Emanative
B
-2

All not working in my netcoreapp3.1 C# Project

This helped (in .vscode/tasks.json):

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "${workspaceFolder}/rest.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary",
                "/unsafe"
            ],
            "problemMatcher": "$msCompile"
        },

works for the 'dotnet build' command, not for the green launch button

also working if executed from the terminal: 'dotnet build -p:unsafe=true'

Buhr answered 3/3, 2020 at 15:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.