繁体   English   中英

在C#asp.net中使用不安全的代码

[英]using unsafe code in C# asp.net

尝试调试修改后的代码以使用unsafe生成错误,我不知道我的代码是否与astrics正确(所以请检查我是否正确输入了代码),尽管除此之外还有另一个问题... asp中的编译器选项.net与Windows应用程序相对,没有可供选择的地方来检查/取消选中使用不安全的选项

据我所知,涉及“手动”处理Web.Config

所以我这样做了,在Web.Config添加了一个代码,有两个版本的用户建议将代码放在配置部分或相同的debug=true范围内...

所以我把它都放进去了

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
 <system.codedom>
   <compilers>
     <compiler language="C#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
   </compilers>
  </system.codedom>
  <connectionStrings>....my secret connection here...
   then rest of configs..
     .....




    struct IO_COUNTERS
    {
        public ulong ReadOperationCount;
        public ulong WriteOperationCount;
        public ulong OtherOperationCount;
        public ulong ReadTransferCount;
        public ulong WriteTransferCount;
        public ulong OtherTransferCount;
    }
    [DllImport("kernel32.dll")]
    unsafe static extern bool GetProcessIoCounters(IntPtr* ProcessHandle, out IO_COUNTERS* IoCounters);


    private struct PROCESS_MEMORY_COUNTERS
    {
        public uint cb;
        public uint PageFaultCount;
        public uint PeakWorkingSetSize;
        public uint WorkingSetSize;
        public uint QuotaPeakPagedPoolUsage;
        public uint QuotaPagedPoolUsage;
        public uint QuotaPeakNonPagedPoolUsage;
        public uint QuotaNonPagedPoolUsage;
        public uint PagefileUsage;
        public uint PeakPagefileUsage;
    }
    [StructLayout(LayoutKind.Sequential, Size = 40)]
    [DllImport("psapi.dll", SetLastError = true)]
    unsafe static extern bool GetProcessMemoryInfo(IntPtr* hProcess, out PROCESS_MEMORY_COUNTERS* Memcounters, int size);

这是实现本机pinvok代码的calss

(在一开始,我试图测试本机vs.托管/.net方法),但在尝试使用pinvoke vs.net之前,我就开始研究海峡以检查pinvoke * unsafe与.net之间的性能。

所以这部分仍然处于“安全模式”下,是否也应该使用astrics处理?

static class Nat
    {
        public static class IO
        {
            public static Dictionary<string, ulong> GetALLIO(Process procToRtrivIO)
            {
                IO_COUNTERS counters;
                Dictionary<string, ulong> retCountIoDict = new Dictionary<string, ulong>();
                GetProcessIoCounters(System.Diagnostics.Process.GetCurrentProcess().Handle, out counters);
                retCountIoDict.Add("ReadOperationCount", counters.ReadOperationCount);
                retCountIoDict.Add("WriteOperationCount", counters.WriteOperationCount);
                retCountIoDict.Add("OtherOperationCount", counters.OtherOperationCount);
                retCountIoDict.Add("ReadTransferCount", counters.ReadTransferCount);
                retCountIoDict.Add("WriteTransferCount", counters.WriteTransferCount);
                retCountIoDict.Add("OtherTransferCount", counters.OtherTransferCount);
                return retCountIoDict;
                //return  "This process has read " + ((counters.ReadTransferCount/1024)/1024).ToString("N0") +
                //    " Mb of data.";

            }
        }
        public static class Mem
        {
            public static Dictionary<string, uint> GetAllMem(Process procToRtrivMem)
            {

                PROCESS_MEMORY_COUNTERS MemCounters;
                Dictionary<string, uint> retCountMemDict = new Dictionary<string, uint>();
                GetProcessMemoryInfo(System.Diagnostics.Process.GetCurrentProcess().Handle, out MemCounters, Marshal.SizeOf(typeof(PROCESS_MEMORY_COUNTERS))); //MemCounters.cb);
                retCountMemDict.Add("cb", MemCounters.cb);
                retCountMemDict.Add("PageFaultCount", MemCounters.PageFaultCount);
                retCountMemDict.Add("PeakWorkingSetSize", MemCounters.PeakWorkingSetSize);
                retCountMemDict.Add("WorkingSetSize", MemCounters.WorkingSetSize);
                retCountMemDict.Add("QuotaPeakPagedPoolUsage", MemCounters.QuotaPeakPagedPoolUsage);
                retCountMemDict.Add("QuotaPagedPoolUsage", MemCounters.QuotaPagedPoolUsage);

                retCountMemDict.Add("QuotaPeakNonPagedPoolUsage", MemCounters.QuotaPeakNonPagedPoolUsage);
                retCountMemDict.Add("QuotaNonPagedPoolUsage", MemCounters.QuotaNonPagedPoolUsage);
                retCountMemDict.Add("PagefileUsage", MemCounters.PagefileUsage);
                retCountMemDict.Add("PeakPagefileUsage", MemCounters.PeakPagefileUsage);

                return retCountMemDict;
                //return  "This process has read " + ((counters.ReadTransferCount/1024)/1024).ToString("N0") +
                //    " Mb of data.";

            }
        }

    }

对此感到抱歉,但更新是我错过了:编译器选项的一部分

compilerOptions="/unsafe" // <<-- you can add this to the compiler config line.

虽然还是。 我的问题只是开始,然后才导致不仅有一个错误:

Unsafe code may only appear if compiling with /unsafe 

但是到处都是错误!

例如第一个:

            public static Dictionary<string, ulong> GetALLIO(Process procToRtrivIO)
            {
                IO_COUNTERS counters;
                Dictionary<string, ulong> retCountIoDict = new Dictionary<string, ulong>();

            --->>   GetProcessIoCounters(System.Diagnostics.Process.GetCurrentProcess().Handle, out counters);


                retCountIoDict.Add("ReadOperationCount", counters.ReadOperationCount);
                retCountIoDict.Add("WriteOperationCount", counters.WriteOperationCount);

该错误是针对调用GetProcesIoCounters()的那一行

错误3参数1:无法从'System.IntPtr'转换为'System.IntPtr *'g:\\ RobDevI5-Raid-0 \\ Documents \\ Visual Studio 2010 \\ WebSites \\ WebSite2 \\ App_Code \\ CsExtensions.cs 416 42 g :. \\ WEBSITE2 \\

UPDAT-代码虽然我无法验证它是否正确使用了不安全的方法,但似乎可以正常工作

不安全签名

    [DllImport("psapi.dll", SetLastError = true)]
    unsafe static extern bool GetProcessMemoryInfo(IntPtr* hProcess, out PROCESS_MEMORY_COUNTERS Memcounters, int size);

我的“不安全”代码

        public static class IO
        {
            public static unsafe Dictionary<string, ulong> GetALLIO(Process procToRtrivIO)
            {
                IO_COUNTERS counters;
                Dictionary<string, ulong> retCountIoDict = new Dictionary<string, ulong>();
                IntPtr* Hw = (IntPtr*)System.Diagnostics.Process.GetCurrentProcess().Handle;
                GetProcessIoCounters(Hw, out counters);
                retCountIoDict.Add("ReadOperationCount", counters.ReadOperationCount);
                retCountIoDict.Add("WriteOperationCount", counters.WriteOperationCount);
                retCountIoDict.Add("OtherOperationCount", counters.OtherOperationCount);
                retCountIoDict.Add("ReadTransferCount", counters.ReadTransferCount);
                retCountIoDict.Add("WriteTransferCount", counters.WriteTransferCount);
                retCountIoDict.Add("OtherTransferCount", counters.OtherTransferCount);
                return retCountIoDict;
                //return  "This process has read " + ((counters.ReadTransferCount/1024)/1024).ToString("N0") +
                //    " Mb of data.";

            }
        }

Necromancing。
接受的答案包含无效的代码。
这是有效的更正版本:

namespace MemoryInfo
{


    class Program
    {

        static void Main(string[] args)
        {
            System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();
            Nat.Mem.GetAllMem(proc);
            Nat.IO.GetALLIO(proc);
        }
    }



    // http://www.pinvoke.net/default.aspx/psapi.getprocessmemoryinfo
    static class Nat
    {


        // [DllImport("kernel32.dll")]
        // public static extern IntPtr GetCurrentProcess();

        [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
        private struct IO_COUNTERS
        {
            public ulong ReadOperationCount;
            public ulong WriteOperationCount;
            public ulong OtherOperationCount;
            public ulong ReadTransferCount;
            public ulong WriteTransferCount;
            public ulong OtherTransferCount;
        }


        [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential, Size = 40)]
        private struct PROCESS_MEMORY_COUNTERS
        {
            public uint cb; // The size of the structure, in bytes (DWORD).
            public uint PageFaultCount; // The number of page faults (DWORD).
            public uint PeakWorkingSetSize; // The peak working set size, in bytes (SIZE_T).
            public uint WorkingSetSize; // The current working set size, in bytes (SIZE_T).
            public uint QuotaPeakPagedPoolUsage; // The peak paged pool usage, in bytes (SIZE_T).
            public uint QuotaPagedPoolUsage; // The current paged pool usage, in bytes (SIZE_T).
            public uint QuotaPeakNonPagedPoolUsage; // The peak nonpaged pool usage, in bytes (SIZE_T).
            public uint QuotaNonPagedPoolUsage; // The current nonpaged pool usage, in bytes (SIZE_T).
            public uint PagefileUsage; // The Commit Charge value in bytes for this process (SIZE_T). Commit Charge is the total amount of memory that the memory manager has committed for a running process.
            public uint PeakPagefileUsage; // The peak value in bytes of the Commit Charge during the lifetime of this process (SIZE_T).
        }


        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        private unsafe static extern bool GetProcessIoCounters(System.IntPtr ProcessHandle, out IO_COUNTERS IoCounters);

        [System.Runtime.InteropServices.DllImport("psapi.dll", SetLastError = true)]
        private unsafe static extern bool GetProcessMemoryInfo(System.IntPtr hProcess, out PROCESS_MEMORY_COUNTERS counters, uint size);


        public static class IO
        {
            unsafe public static System.Collections.Generic.Dictionary<string, ulong> GetALLIO(System.Diagnostics.Process procToRtrivIO)
            {
                IO_COUNTERS counters;
                System.Collections.Generic.Dictionary<string, ulong> retCountIoDict = 
                    new System.Collections.Generic.Dictionary<string, ulong>();
                System.IntPtr ptr = System.Diagnostics.Process.GetCurrentProcess().Handle;

                GetProcessIoCounters(ptr, out counters);
                retCountIoDict.Add("ReadOperationCount", counters.ReadOperationCount);
                retCountIoDict.Add("WriteOperationCount", counters.WriteOperationCount);
                retCountIoDict.Add("OtherOperationCount", counters.OtherOperationCount);
                retCountIoDict.Add("ReadTransferCount", counters.ReadTransferCount);
                retCountIoDict.Add("WriteTransferCount", counters.WriteTransferCount);
                retCountIoDict.Add("OtherTransferCount", counters.OtherTransferCount);
                return retCountIoDict;
                //return  "This process has read " + ((counters.ReadTransferCount/1024)/1024).ToString("N0") +
                //    " Mb of data.";

            }
        } // End Class IO 


        public static class Mem
        {
            unsafe public static System.Collections.Generic.Dictionary<string, uint> GetAllMem(System.Diagnostics.Process procToRtrivMem)
            {
                PROCESS_MEMORY_COUNTERS MemCounters;
                System.Collections.Generic.Dictionary<string, uint> retCountMemDict = 
                    new System.Collections.Generic.Dictionary<string, uint>();
                System.IntPtr ptr = System.Diagnostics.Process.GetCurrentProcess().Handle;
                uint nativeStructSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(PROCESS_MEMORY_COUNTERS));


                GetProcessMemoryInfo(ptr, out MemCounters, nativeStructSize); //MemCounters.cb);
                retCountMemDict.Add("cb", MemCounters.cb);
                retCountMemDict.Add("PageFaultCount", MemCounters.PageFaultCount);
                retCountMemDict.Add("PeakWorkingSetSize", MemCounters.PeakWorkingSetSize);
                retCountMemDict.Add("WorkingSetSize", MemCounters.WorkingSetSize);
                retCountMemDict.Add("QuotaPeakPagedPoolUsage", MemCounters.QuotaPeakPagedPoolUsage);
                retCountMemDict.Add("QuotaPagedPoolUsage", MemCounters.QuotaPagedPoolUsage);

                retCountMemDict.Add("QuotaPeakNonPagedPoolUsage", MemCounters.QuotaPeakNonPagedPoolUsage);
                retCountMemDict.Add("QuotaNonPagedPoolUsage", MemCounters.QuotaNonPagedPoolUsage);
                retCountMemDict.Add("PagefileUsage", MemCounters.PagefileUsage);
                retCountMemDict.Add("PeakPagefileUsage", MemCounters.PeakPagefileUsage);

                return retCountMemDict;
                //return  "This process has read " + ((counters.ReadTransferCount/1024)/1024).ToString("N0") +
                //    " Mb of data.";
            }


        } // End Class Mem

    }




}

我认为您的网络配置行缺少compileOptions =“ / unsafe +”部分

例如

        <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" compilerOptions="/unsafe+" warningLevel="4" />
    </compilers>

听起来您需要了解星号所代表的含义。 与其他类似C的语言一样,在C#中,它表示指针类型。 例如:

int *

...表示“指向int的指针”。 即,此变量的值指示包含int的内存位置。 C#和其他.NET语言实现了一种称为“类型安全”的类型,这意味着很难误解内存中的值(例如,尝试在实际包含int的内存位置读取字符串),这在很大程度上是有用的事情。 但是,有时,当您与本机代码交互时,能够处理指针是很有用的。 这将破坏类型安全机制,因此必须将代码标记为unsafe并且如前所述,需要使用/unsafe开关进行编译。

您似乎建议您在p /调用和使用不安全的代码之间做出选择。 以我的经验,这种情况很少发生,因为存在两种解决不同问题的技术。 P / invoke允许您以通常不需要使用不安全代码的方式与本机代码进行交互,但实际上,这取决于您要与之交互的本机代码的性质。

当您询问您的“安全模式”代码是否“是否也应使用​​astrics对待”? 我希望我的解释可以告诉您,您不会将代码带有星号对待,而是根据具体情况根据需要声明变量。

另外,您对GetProcessIoCounters p / invoke声明看起来是错误的。 您很少看到类型为IntPtr *的参数。 查看http://pinvoke.net查找正确的声明。

为了清除更多术语,可以对代码进行托管或非托管。 C#代码始终处于托管状态。 非托管代码将使用多种语言之一编写,例如C,C ++等。C#代码始终受管,但可以是类型安全的(默认),也可以将C#代码块标记为不安全的,这使您可以使用指针类型。

好的,您需要更改一些内容,如下所示

using System.Collections.Generic;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;
static class Nat
{
    [StructLayout(LayoutKind.Sequential]
    struct IO_COUNTERS
    {
        public ulong ReadOperationCount;
        public ulong WriteOperationCount;
        public ulong OtherOperationCount;
        public ulong ReadTransferCount;
        public ulong WriteTransferCount;
        public ulong OtherTransferCount;
    }
    [DllImport("kernel32.dll")]
    unsafe static extern bool GetProcessIoCounters(IntPtr ProcessHandle, out IO_COUNTERS IoCounters);

    [StructLayout(LayoutKind.Sequential, Size = 40)]
    private struct PROCESS_MEMORY_COUNTERS
    {
        public uint cb;
        public uint PageFaultCount;
        public uint PeakWorkingSetSize;
        public uint WorkingSetSize;
        public uint QuotaPeakPagedPoolUsage;
        public uint QuotaPagedPoolUsage;
        public uint QuotaPeakNonPagedPoolUsage;
        public uint QuotaNonPagedPoolUsage;
        public uint PagefileUsage;
        public uint PeakPagefileUsage;
    }

    [DllImport("psapi.dll", SetLastError = true)]
    unsafe static extern bool GetProcessMemoryInfo(IntPtr* hProcess, out PROCESS_MEMORY_COUNTERS* Memcounters, int size);

    public static class IO
    {
        unsafe public static Dictionary<string, ulong> GetALLIO(Process procToRtrivIO)
        {
            IO_COUNTERS counters;
            Dictionary<string, ulong> retCountIoDict = new Dictionary<string, ulong>();
            IntPtr ptr = System.Diagnostics.Process.GetCurrentProcess().Handle;

            GetProcessIoCounters(ptr, out counters);
            retCountIoDict.Add("ReadOperationCount", counters.ReadOperationCount);
            retCountIoDict.Add("WriteOperationCount", counters.WriteOperationCount);
            retCountIoDict.Add("OtherOperationCount", counters.OtherOperationCount);
            retCountIoDict.Add("ReadTransferCount", counters.ReadTransferCount);
            retCountIoDict.Add("WriteTransferCount", counters.WriteTransferCount);
            retCountIoDict.Add("OtherTransferCount", counters.OtherTransferCount);
            return retCountIoDict;
            //return  "This process has read " + ((counters.ReadTransferCount/1024)/1024).ToString("N0") +
            //    " Mb of data.";

        }
    }
    public static class Mem
    {
        unsafe public static Dictionary<string, uint> GetAllMem(Process procToRtrivMem)
        {

            PROCESS_MEMORY_COUNTERS* MemCounters;
            Dictionary<string, uint> retCountMemDict = new Dictionary<string, uint>();
            IntPtr ptr = System.Diagnostics.Process.GetCurrentProcess().Handle;

            GetProcessMemoryInfo(&ptr, out MemCounters, Marshal.SizeOf(typeof(PROCESS_MEMORY_COUNTERS))); //MemCounters.cb);
            retCountMemDict.Add("cb", MemCounters->cb);
            retCountMemDict.Add("PageFaultCount", MemCounters->PageFaultCount);
            retCountMemDict.Add("PeakWorkingSetSize", MemCounters->PeakWorkingSetSize);
            retCountMemDict.Add("WorkingSetSize", MemCounters->WorkingSetSize);
            retCountMemDict.Add("QuotaPeakPagedPoolUsage", MemCounters->QuotaPeakPagedPoolUsage);
            retCountMemDict.Add("QuotaPagedPoolUsage", MemCounters->QuotaPagedPoolUsage);

            retCountMemDict.Add("QuotaPeakNonPagedPoolUsage", MemCounters->QuotaPeakNonPagedPoolUsage);
            retCountMemDict.Add("QuotaNonPagedPoolUsage", MemCounters->QuotaNonPagedPoolUsage);
            retCountMemDict.Add("PagefileUsage", MemCounters->PagefileUsage);
            retCountMemDict.Add("PeakPagefileUsage", MemCounters->PeakPagefileUsage);

            return retCountMemDict;
            //return  "This process has read " + ((counters.ReadTransferCount/1024)/1024).ToString("N0") +
            //    " Mb of data.";

        }
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM