IntPtr、Struct 相互转换
一般写c#代码基本用不到 相互转换 只有调用c++中的dll动态库的时候才用的到
struct转intptr
public static IntPtr StructToIntPtr<T>(T req) where T : struct
{
int size = Marshal.SizeOf(req);
byte[] bytes = new byte[size];
IntPtr structPtr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(req, structPtr, false);
Marshal.Copy(structPtr, bytes, , size);
return structPtr;
}
用完intptr记得释放申请的这块内存(Marshal.FreeHGlobal(IntPtr);)
Intptr转struct
public static T IntPtrToStruct<T>(IntPtr ptr) where T : struct
{
object t = Marshal.PtrToStructure(ptr, typeof(T));
Marshal.FreeHGlobal(ptr);
if (t is T t1)
{
return t1;
}
else
{
return default(T);
}
}
IntPtr、Struct 相互转换的更多相关文章
- C# byte[]、struct、intptr等的相互转换
1.struct byte[]互相转换 //struct转换为byte[] public static byte[] StructToBytes(object structObj) { int siz ...
- [转载]C#中int和IntPtr相互转换
方法一. int转IntPtr int i = 12; IntPtr p = new IntPtr(i); IntPtr转int int myi = (int)p; ...
- (一)一个工作任务引起的乱战——c#中结构体与byte[]间相互转换
一个工作任务涉及到c#与c++系统间的udp通信,处理了蛮长时间没有完成任务,但是期间接触到不少小知识点.本人是初接触c#,c++语言没有接触过.可能写的东西都很小儿科,暂且记录下来当工作日记把. 先 ...
- 如何让IntPtr指向一块内存,以及托管内存与非托管内存的相互转化
IntPtr idp= IntPtr.Zero; StringBuilder idata = new StringBuilder("000000"); string idata = ...
- C# Struct结构体里数组长度的指定
typedef struct Point{ unsigned short x; unsigned short y; }mPoint;//点坐标 typedef struct Line{ mPoint ...
- 关于C# byte[]与struct的转换
转自:http://blog.chinaunix.net/uid-215617-id-2213082.html Some of the C# code I've been writing recent ...
- IntPtr与自定义结构互转
//IntPtr转自定义结构 struct onlydata { IntPtr hwnd; }; onlydata pd=new onlydata(); IntPtr pd; pd=Marshal.P ...
- 转:struct sockaddr与struct sockaddr_in ,struct sockaddr_un的区别和联系
在linux环境下,结构体struct sockaddr在/usr/include/linux/socket.h中定义,具体如下:typedef unsigned short sa_family_t; ...
- 使用Marshal.Copy把Txt行数据转为Struct类型值
添加重要的命名空间: using System.Runtime.InteropServices; 先建立结构相同(char长度相同)的Struct类型用于转换: [StructLayout(Layou ...
随机推荐
- #define 和常量 const 的区别
const 后的常量,程序对其中只能读不能修改. #include <iostream> using namespace std; int main() { const double pi ...
- hdu4176 水题
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; #def ...
- python 异常处理技巧
- python 六种典型的异常
- Launch configuration JUnitCore references non-existing project XXX.
- C#面向对象基础--类与对象
1.类与对象 类是面向对象编程的基本单元:类造出来的变量叫对象. 一个类包含俩种成员:字段与方法. 字段即变量,方法即函数. 面向对象思想:教给我们如何合理的运用类的规则去编写代码. 2.类的字段 字 ...
- 前端知识---html
HTML HTML是英文Hyper Text Mark-up Language(超文本标记语言)的缩写,他是一种制作万维网页面标准语言(标记).相当于定义统一的一套规则,大家都来遵守他,这样就可以让浏 ...
- [Offer收割]编程练习赛108 - 树上的最短边 树链剖分
直接点权下放到边权,每次查询从dfs序的st[u]+1,ed[v]之间查询, #include<iostream> #include<stdio.h> #include< ...
- springmvc 返回json数据给前台jsp页面展示
spring mvc返回json字符串的方式 方案一:使用@ResponseBody 注解返回响应体 直接将返回值序列化json 优点:不需要自己再处理 步骤一:在spring- ...
- 2018-8-10-git-使用-VisualStudio-比较分支更改
title author date CreateTime categories git 使用 VisualStudio 比较分支更改 lindexi 2018-08-10 19:16:52 +0800 ...