C#里使用CopyMemory

Socket接收到的byte []要转换成自定义的struct / 自定义Struct转换成byte []都相当麻烦
用循环去转换太浪费时间了……于是想到用CopyMemory,Google一圈终于搞定
下面的代码是在Snippet Compiler里编译通过的

C#代码
#region Imports   
using System;   
using System.IO;   
using System.Net;   
using System.Xml;   
using System.Text;   
using System.Data;   
using System.Drawing;   
using System.Threading;   
using System.Reflection;   
using System.Collections;   
using System.Net.Sockets;   
using System.Windows.Forms;   
using System.ComponentModel;   
using System.Drawing.Imaging;   
using System.Security.Cryptography;   
using System.Runtime.InteropServices;   
using System.Text.RegularExpressions;  
#endregion  
#region Assembly Info   
[assembly: AssemblyTitle("Test Application by eglic")]   
[assembly: AssemblyDescription("Test Application by eglic")]   
[assembly: AssemblyConfiguration("")]   
[assembly: AssemblyCompany("eGlic.Com")]   
[assembly: AssemblyProduct("Test Application by eglic")]   
[assembly: AssemblyCopyright("Copyright (C) eGlic.Com 2007")]   
[assembly: AssemblyTrademark("eGlic.Com")]   
[assembly: AssemblyCulture("")]   
[assembly: ComVisible(false)]   
[assembly: AssemblyVersion("1.0.0.0")]   
[assembly: AssemblyFileVersion("1.0.0.0")]  
#endregion   
  
namespace eGlic   
{  
    #region Application Entrance   
    public class Test{   
        [STAThread]   
        public static void Main() {   
            byte [] buffer=new byte [20];   
            DataGraphHeader header=new DataGraphHeader();   
            string data="ABCDEFGH";   
               
            header.Signature=0xFF;   
            header.Protocol.Type=1;   
            header.Protocol.Version=1;   
            header.Type=99;   
            header.SerialID=1234567;   
            header.Size=8;   
               
            Win32API.CopyMemoryEx(buffer,ref header);   
            Win32API.CopyMemoryEx(buffer,12,System.Text.Encoding.ASCII.GetBytes(data),0,8);   
               
            string o="";   
            for(int i=0;i<buffer.Length;i++){   
                if(buffer[i]<10) o+="0";   
                o+=String.Format("{0:X}",buffer[i]);   
                o+=" ";   
            }   
            MessageBox.Show(o,"转成Byte []之后的数据包",MessageBoxButtons.OK,MessageBoxIcon.Information);   
               
            DataGraphHeader h=new DataGraphHeader();   
            byte [] buf;   
            string d="";   
               
            Win32API.CopyMemoryEx(ref h,buffer);   
            buf=new byte [h.Size];   
            Win32API.CopyMemoryEx(buf,buffer,12,h.Size);   
               
            o="h.Signature=" +h.Signature.ToString()+"/r/n";   
            o+="h.Protocol.Type=" +h.Protocol.Type.ToString()+"/r/n";   
            o+="h.Protocol.Version=" +h.Protocol.Version.ToString()+"/r/n";   
            o+="h.Type=" +h.Type.ToString()+"/r/n";   
            o+="h.SerialID=" +h.SerialID.ToString()+"/r/n";   
            o+="h.Size=" +h.Size.ToString()+"/r/n";   
            o+="附加数据为:"+System.Text.Encoding.ASCII.GetString(buf);   
            MessageBox.Show(o,"解析后数据包",MessageBoxButtons.OK,MessageBoxIcon.Information);   
        }   
           
    }  
    #endregion  
      
    #region Win32API   
    public class Win32API {   
        [DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory", CharSet = CharSet.Ansi)]   
        public extern static long CopyMemory(IntPtr dest, IntPtr source, int size);  
        #region CopyMemoryEx   
        /// <summary>   
        /// CopyMemoryEx   
        /// </summary>   
        /// <param name="dest">目标缓存区</param>   
        /// <param name="source">DataGraphPackage</param>   
        /// <returns></returns>   
        public unsafe static long CopyMemoryEx(byte[] dest, ref DataGraphHeader source) {   
            return CopyMemoryEx(dest, 0,ref source);   
        }   
        /// <summary>   
        /// CopyMemoryEx   
        /// </summary>   
        /// <param name="dest">目标缓存区</param>   
        /// <param name="DestStart">目标缓存区中的开始位置</param>   
        /// <param name="source">DataGraphPackage</param>   
        /// <returns></returns>   
        public unsafe static long CopyMemoryEx(byte[] dest,int DestStart, ref DataGraphHeader source) {   
            IntPtr dp;   
            IntPtr sp;   
            fixed (byte* ds = &dest[DestStart]) {   
                fixed (DataGraphHeader* sr = &source) {   
                    dp = (IntPtr)ds;   
                    sp = (IntPtr)sr;   
                    return CopyMemory(dp, sp, sizeof(DataGraphHeader));   
                }   
            }   
        }   
        /// <summary>   
        /// CopyMemoryEx   
        /// </summary>   
        /// <param name="dest">DataGraphPackage</param>   
        /// <param name="source">源数据缓存</param>   
        /// <returns></returns>   
        public unsafe static long CopyMemoryEx(ref DataGraphHeader dest, byte[] source) {   
            return CopyMemoryEx(ref dest, source, 0);   
        }   
        /// <summary>   
        /// CopyMemoryEx   
        /// </summary>   
        /// <param name="dest">DataGraphPackage</param>   
        /// <param name="source">源数据缓存</param>   
        /// <returns></returns>   
        public unsafe static long CopyMemoryEx(ref DataGraphHeader dest, byte[] source,int SourceStart) {   
            IntPtr dp;   
            IntPtr sp;   
            fixed (DataGraphHeader* ds = &dest) {   
                fixed (byte* sr = &source[SourceStart]) {   
                    dp = (IntPtr)ds;   
                    sp = (IntPtr)sr;   
                    return CopyMemory(dp, sp, sizeof(DataGraphHeader));   
                }   
            }   
        }   
        /// <summary>   
        /// CopyMemoryEx   
        /// </summary>   
        /// <param name="dest">目标缓存</param>   
        /// <param name="source">源数据</param>   
        /// <param name="size">要从源数据中复制的长度</param>   
        /// <returns></returns>   
        public unsafe static long CopyMemoryEx(byte[] dest, byte[] source, int size) {   
            return CopyMemoryEx(dest, 0, source, 0, size);   
        }   
        /// <summary>   
        /// CopyMemoryEx   
        /// </summary>   
        /// <param name="dest">目标缓存</param>   
        /// <param name="source">源数据</param>   
        /// <param name="SourceStart">源数据缓存中开始位置</param>   
        /// <param name="size">要从源数据中复制的长度</param>   
        /// <returns></returns>   
        public unsafe static long CopyMemoryEx(byte[] dest, byte[] source, int SourceStart,int size) {   
            return CopyMemoryEx(dest, 0, source, SourceStart, size);   
        }   
        /// <summary>   
        /// CopyMemoryEx   
        /// </summary>   
        /// <param name="dest">目标缓存</param>   
        /// <param name="DestStart">目标缓存中开始复制的位置</param>   
        /// <param name="source">源数据</param>   
        /// <param name="SourceStart">源数据缓存中开始位置</param>   
        /// <param name="size">要从源数据中复制的长度</param>   
        /// <returns></returns>   
        public unsafe static long CopyMemoryEx(byte[] dest,int DestStart, byte[] source, int SourceStart, int size) {   
            IntPtr dp;   
            IntPtr sp;   
            fixed (byte* ds = &dest[DestStart]) {   
                fixed (byte* sr = &source[SourceStart]) {   
                    dp = (IntPtr)ds;   
                    sp = (IntPtr)sr;   
                    return CopyMemory(dp, sp, size);   
                }   
            }   
        }  
        #endregion   
    }  
    #endregion   
       
    [StructLayout(LayoutKind.Sequential)]   
    public struct ProtocolInfo {   
        public byte Type;   
        public byte Version;   
    }   
       
    [StructLayout(LayoutKind.Sequential)]   
    public struct DataGraphHeader {   
        public byte Signature;              //包头:    1字节   
        public ProtocolInfo Protocol;       //协议:    2字节   
        public byte Type;                   //包类型:  1字节   
        public uint SerialID;               //包序号    4字节   
        public int Size;                    //包尺寸    4字节   
    }   
}  


本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/Python/archive/2007/08/24/1757002.aspx

基于 NSFW Model 色情图片识别鉴黄 后面更新视频检测 项目背景: 随着互联网的快速发展,网络上的信息量呈现出爆炸式的增长。然而,互联网上的内容良莠不齐,其中不乏一些不良信息,如色情、暴力等。这些信息对青少年的健康成长和社会风气产生了不良影响。为了净化网络环境,保护青少年免受不良信息的侵害,我国政府加大了对网络内容的监管力度。在此背景下,本项目应运而生,旨在实现对网络图片和视频的自动识别与过滤,助力构建清朗的网络空间。 项目简介: 本项目基于 NSFW(Not Safe For Work)Model,利用深度学习技术对色情图片进行识别与鉴黄。NSFW Model 是一种基于卷积神经网络(CNN)的图像识别模型,通过学习大量的色情图片和非色情图片,能够准确地判断一张图片是否含有色情内容。本项目在 NSFW Model 的基础上,进一步优化了模型结构,提高了识别的准确率和效率。 项目功能: 色情图片识别:用户上传图片后,系统会自动调用 NSFW Model 对图片进行识别,判断图片是否含有色情内容。如果含有色情内容,系统会给出相应的提示,并阻止图片的传播。 视频检测:针对网络视频,本项目采用帧提取技术,将视频分解为一帧帧图片,然后使用 NSFW Model 对这些图片进行识别。如果检测到含有色情内容的图片,系统会给出相应的提示,并阻止视频的传播。 实时监控:本项目可应用于网络直播、短视频平台等场景,实时监控画面内容,一旦检测到含有色情内容的画面,立即进行屏蔽处理,确保网络环境的纯洁。
### 如何在本地部署 NSFW 模型或服务 要在本地环境中成功部署 NSFW(不适宜工作场合内容)检测模型或服务,以下是详细的说明: #### 准备环境 为了确保能够顺利运行模型和服务,需要安装必要的依赖项。这些工具和库包括但不限于以下几类: - **Python 环境**: 推荐使用 Python 3.7 或更高版本。 - **Transformers 库**: 提供加载预训练模型的功能[^1]。 - **PyTorch/TensorFlow**: 支持深度学习框架的计算需求。 - **Pillow (PIL)**: 处理图像文件并将其转换为适合输入模型的形式。 具体命令如下所示: ```bash pip install transformers torch Pillow ``` #### 加载模型与测试 通过 Hugging Face 的 `transformers` 工具包可以直接访问已有的 NSFW 图片分类模型。例如,可以采用名为 `"Falconsai/nsfw_image_detection"` 的公开模型来完成此任务[^1]。 下面是一个简单的代码片段展示如何加载该模型并对单张图片执行预测操作: ```python from PIL import Image from transformers import pipeline def classify_nsfw(image_path): # 打开指定路径下的图片文件 img = Image.open(image_path) # 初始化 image-classification 流水线对象,并指明使用的特定模型名称 classifier = pipeline("image-classification", model="Falconsai/nsfw_image_detection") # 对传入的图片调用流水线方法得到其类别标签及其置信度分数列表形式的结果 result = classifier(img) return result if __name__ == "__main__": test_img_path = "<your_test_image>" output_results = classify_nsfw(test_img_path) print(output_results) ``` 注意替换 `<your_test_image>` 成实际存在的图片绝对或者相对地址字符串值之前再尝试运行以上脚本。 #### 构建 RESTful API 服务 如果希望进一步扩展功能至 Web 应用程序层面,则可考虑利用 Flask/Django 这样的轻量级 web 开发框架构建起支持 HTTP 请求交互的服务端接口。这里给出基于 FastAPI 实现的一个简单例子作为示范用途: ```python import uvicorn from fastapi import FastAPI, File, UploadFile from PIL import Image from io import BytesIO from typing import List from pydantic import BaseModel app = FastAPI() class Prediction(BaseModel): label: str score: float @app.post("/predict/", response_model=List[Prediction]) async def predict(file: UploadFile = File(...)): try: contents = await file.read() pil_image = Image.open(BytesIO(contents)) clf_pipeline = pipeline('image-classification', model='Falconsai/nsfw_image_detection') predictions = clf_pipeline(pil_image) formatted_preds = [{"label": pred['label'], "score": round(pred['score'], 4)} for pred in predictions] return formatted_preds except Exception as e: raise ValueError(f"Error processing uploaded file {e}") if __name__ == '__main__': uvicorn.run(app, host='0.0.0.0', port=8000) ``` 启动服务器之后即可向 `/predict/` 路径发送 POST 请求附带上传待分析的目标图片获取返回结果了。 ---
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值