Share via


CA2149: Transparent methods must not call into native code

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Item Value
TypeName TransparentMethodsMustNotCallNativeCode
CheckId CA2149
Category Microsoft.Security
Breaking Change Breaking

Cause

A method calls a native function through a method stub such as P/Invoke.

Rule Description

This rule fires on any transparent method which calls directly into native code, for example, through a P/Invoke. Violations of this rule lead to a MethodAccessException in the level 2 transparency model, and a full demand for UnmanagedCode in the level 1 transparency model.

How to Fix Violations

To fix a violation of this rule, mark the method that calls the native code with the SecurityCriticalAttribute or SecuritySafeCriticalAttribute attribute.

When to Suppress Warnings

Do not suppress a warning from this rule.

Example

using System;
using System.Runtime.InteropServices;

namespace TransparencyWarningsDemo
{

    public class CallNativeCodeClass
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool Beep(uint dwFreq, uint dwDuration);

        public void CallNativeMethod()
        {
            // CA2149 violation - transparent method calling native code
            Beep(10000, 1);
        }
    }

}