当前位置:网站首页>C# unsafe 非托管对象指针转换
C# unsafe 非托管对象指针转换
2022-07-24 14:00:00 【墨池象牙白】
今天被大佬用unsafe秀了一波,稍微记录一下
如何获取指针所指的非托管对象(这里是结构体)AsRef
以及反过来,用非托管对象获取对应的指针 AsPointer
struct A_Part
{
public int f1;
public int f2;
}
unsafe class Program
{
static T* Alloc<T>(int size = 1) where T : unmanaged
{
Console.WriteLine(Marshal.SizeOf<T>());
IntPtr begin = Marshal.AllocHGlobal(Marshal.SizeOf<T>() * size);
return (T*)begin;
}
static ref T ToRef<T>(void* ptr) => ref Unsafe.AsRef<T>(ptr);
static T* ToPointer<T>(ref T value) where T : unmanaged => (T*)Unsafe.AsPointer(ref value);
static void Free(void* begin)
{
Marshal.FreeHGlobal((IntPtr)begin);
}
static void Main(string[] args)
{
A_Part* ptr = Alloc<A_Part>();
ptr->f1 = 1;
Console.WriteLine($"original ptr f1:{ptr->f1}");
A_Part a = *ptr;
a.f1 = 2;
Console.WriteLine($"after A ptr f1:{ptr->f1}");
ref A_Part reft = ref ToRef<A_Part>(ptr);
reft.f1 = 3;
Console.WriteLine($"after ref ptr f1:{ptr->f1}");
A_Part* ref_ptr = ToPointer(ref reft);
Console.WriteLine($"ref_ptr f1:{ref_ptr->f1}");
Free(ptr);
Console.ReadKey();
}
}边栏推荐
- OC sets the image fillet, and the image is not deformed
- Csp2021 T3 palindrome
- 在LNMP架构中搭建Zabbix监控服务
- Nessus security testing tool tutorial
- 微信小程序 TODO案例
- 栈与队列——225. 用队列实现栈
- Remove the treasure box app with the green logo that cannot be deleted from iPhone
- Unity行人随机行走不碰撞
- R语言使用epiDisplay包的summ函数计算dataframe中指定变量在不同分组变量下的描述性统计汇总信息并可视化有序点图、自定义cex.main参数配置标题文本字体的大小
- 交换机链路聚合详解【华为eNSP】
猜你喜欢

【无标题】

2022.7.22 simulation match

【C语言笔记分享】——动态内存管理malloc、free、calloc、realloc、柔性数组

Network security -- Service Vulnerability scanning and utilization

Matlab program for natural gas flow calculation

rhcsa第六次笔记

Apache2 ha experiment with raspberry pie

Chapter VI bus

JS execution mechanism

Network security - file upload blacklist bypass
随机推荐
R语言检验样本比例:使用prop.test函数执行单样本比例检验计算总体中成功样本比例p值的置信区间
Detailed analysis of common command modules of ansible service
Introduction to the separation of front and rear platforms of predecessors
CSDN垃圾的没有底线!
Flink fault tolerance mechanism (V)
在EXCEL表格中如何进行快速换行
No response to NPM instruction
The solution to the error of [installation detects that the primary IP address of the system is the address assigned by DHCP] when installing Oracle10g under win7
Ansible服务常用命令模块详细解析
Explain flex layout in detail
[机缘参悟-51]:既然人注定要死亡,为什么还要活着?
Solve the problem of repeated clicking of button uibutton
Mmdrawercontroller gets the current VC for push and pop
How to install PHP 5.6 on Ubuntu 18.04 and Debian 9
Network security - file upload whitelist bypass
Network security - file upload competitive conditions bypass
The fourth edition of probability and mathematical statistics of Zhejiang University proves that the absolute value of the correlation coefficient of random variables X and Y is less than 1, and some
Network security -- Service Vulnerability scanning and utilization
Was installer startup error
Flink综合案例(九)