Interop c++ struct in c# variable string size
i transfer over ipc a struct from unmanaged into managed code. Is it possible to transfer a string without set a constant size or fill the rest auf the bytes into the last member of the struct ?
c++ struct
typedef union
{
struct
{
int id;
string Data;
};
开发者_StackOverflowchar bytes[];
} SocketData;
c# struct
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SocketData
{
public int id;
public string Data;
}
Convert bytes to struct
public static object RawDeserialize(byte[] rawData, int position, Type anyType)
{
var rawsize = rawData.Length;
//if (rawsize > rawData.Length)
// return null;
var buffer = Marshal.AllocHGlobal(rawsize);
Marshal.Copy(rawData, position, buffer, rawsize);
var retobj = Marshal.PtrToStructure(buffer, anyType);
Marshal.FreeHGlobal(buffer);
return retobj;
}
Do not do that, std::string
is not POD.
Even with different compiler/linker versions std::string
is NOT binary compatible*, you cannot expect it to be compatible between managed and unmanaged world.
* By this I mean, If you have a DLL build using XX compiler version (even of same vendor), and passing std::string
from a client (EXE), which is built using older/newer compiler/header version - the string
object may not be same.
This other post might help you.
It involves using StringBuilder instead.
I wonder why you need variable buffer lengths since Sockets usually use fixed length buffers
精彩评论