将C#转换为带有Marshal问题的C ++

时间:2012-05-15 15:16:05

标签: c# c++ marshalling unmarshalling

我在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();

我不熟悉Marshaling。

1 个答案:

答案 0 :(得分: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 ++。