Search code examples
c#c++marshallingunmarshalling

Converting C# to C++ with Marshal problems


I have these declarations in 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");

I want to convert these code lines from C# to 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();

I am not familiar with Marshaling.


Solution

  • I don't know C++ but I do know marshalling so here's what the lines are doing

    //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();
    

    I can't see why you'd actually need to convert most of this to C++, the point of Marshalling is about making managed objects available to unmanaged code and converting unmanaged objects into managed ones, which if you're operating all in C++ you shouldn't really need to do, even if it's managed C++.