-1

我在 C++ 中有这些声明:

struct objectStruct;

int positionMemory = getPosition();

short size = getSize();

void *allocatedObject; // Originally, it is in C#: IntPtr allocatedObject { get; private set; }

byte[] byteName = Encoding.ASCII.GetBytes("Hello There");

我想将这些代码行从 C# 转换为 C++:

string result = Marshal.PtrToStringAnsi(new IntPtr(positionMemory), size); 

Marshal.StructureToPtr(objectStruct, new IntPtr(positionMemory), true);

Marshal.Copy(byteName, 0, new IntPtr(positionMemory), size);

long posInMemory = allocatedObject.Offset(size).ToInt64();

我对编组不熟悉。

4

1 回答 1

1

我不知道 C++,但我知道编组所以这就是这些行在做什么

//Get size number of characters of the string pointed to by the positionMemory pointer.
string result = Marshal.PtrToStringAnsi(new IntPtr(positionMemory), size); 

//Copy the contents of objectStruct to the memory location pointed at by positionMemory
Marshal.StructureToPtr(objectStruct, new IntPtr(positionMemory), true);

//Copy size number of bytes from the byteName array starting at index 0 to the memory indicated by positionMemory
Marshal.Copy(byteName, 0, new IntPtr(positionMemory), size);

//I think offsetting the memory location indicated by allocatedObject by size number of bytes and converting the memory pointer to an Int64.
machineNamePosInMem = allocatedObject.Offset(size).ToInt64();

我不明白为什么您实际上需要将其中的大部分转换为 C++,编组的重点是使托管对象可用于非托管代码并将非托管对象转换为托管对象,如果您在 C++ 中进行操作,那么您不应该真的需要这样做,即使它是托管的 C++。

于 2012-05-15T15:29:30.570 回答