2012-05-15 61 views
-1

我在C++這些聲明:轉換C#和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(); 

我不熟悉的封送處理。

+0

什麼問題?你想做什麼? C++聲明與C#代碼有什麼關係(從您展示的內容中不完全清楚)? – Kiril

+0

我需要將一些C#代碼轉換爲C++,並面臨如何從C#轉換爲C++編譯上述對象的問題 – olidev

回答

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++,點Marshalling的目標是讓託管對象可用於非託管代碼,並將非託管對象轉換爲託管對象,如果您使用C++進行全部操作,即使託管C++,也不需要執行此操作。

+0

偉大的答案!非常感謝! – olidev