简体   繁体   English

C#中的指针数学

[英]Pointer math in C#

I am trying to use some pinvoke code to call a C function.我正在尝试使用一些 pinvoke 代码来调用 C 函数。 The function fills a buffer with data.该函数用数据填充缓冲区。

The structure is set up as a DWORD for the length, followed by a string.该结构被设置为长度的 DWORD,后跟一个字符串。 How do I extract the string from the IntPtr?如何从 IntPtr 中提取字符串?

 IntPtr buffer = Marshal.AllocHGlobal(nRequiredSize);
 PInvokedFunction(buffer, nRequiredSize);
 string s = Marshal.PtrToStringAuto(buffer + 4); //this is an error.
 Marshal.FreeHGlobal(buffer);

You should do this:你应该做这个:

IntPtr sBuffer = new IntPtr( buffer.ToInt64() + 4 );
string s = Marshal.PtrToStringAuto( sBuffer );

So your code is 64bit safe.所以你的代码是 64 位安全的。

The best I could come up with was the following, though the use of the UnmanagedMemoryStream seems a bit of a hack.我能想到的最好的是以下内容,尽管使用 UnmanagedMemoryStream 似乎有点黑客。

 IntPtr buffer = Marshal.AllocHGlobal((int)nRequiredSize);
 PInvokedFunction(buffer, nRequiredSize);
 UnmanagedMemoryStream memStream = new UnmanagedMemoryStream(buffer.ToPointer(), nRequiredSize);
 memStream.Seek(4, SeekOrigin.Begin);
 IntPtr ptr = new IntPtr(memStream.PositionPointer);
 string s = Marshal.PtrToStringAuto(ptr);
 Marshal.FreeHGlobal(buffer);

This seemed to work, although I think I like Matt Ellis's Answer better.这似乎有效,尽管我认为我更喜欢Matt Ellis 的答案

I changed the IntPtr on the [DllImport] to a byte[].我将 [DllImport] 上的 IntPtr 更改为 byte[]。

 //allocate the buffer in .Net
 byte[] buffer = new byte[nRequiredSize];

 //call the WIN32 function, passing it the allocated buffer
 PInvokedFunction(buffer);

 //get the string from the 5th byte
 string s = Marshal.PtrToStringAuto(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 4));

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

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