How to pass char * to struct from C # to C ++

It seems to me that my problem is similar to this .

So far, I have a structure defined in C ++, for example:

typedef struct struct_type1 { uint64 nameLen; char * name; } STATUSSTRUCT; 

and a function defined as:

 extern int _stdcall getStatus(STATUSSTRUCT * status); 

and, presumably, such a function:

 int _stdcall getStatus(STATUSSTRUCT * status) { status->nameLen = someLength; status->name = someName; return 1; } 

Please note that I cannot actually change the C ++ code (for various reasons) and the header file.

My C # code is as follows:

 public struct STATUSSTRUCT { public UInt64 nameLen; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4128)] public byte[] name; } STATUSSTRUCT status; [DllImport("test.dll", CallingConvention = CallingConvention.StdCall)] public static extern int getStatus(ref STATUSSTRUCT status); public void refreshStatus() { status = new STATUSSTRUCT(); status.nameLen = 4128; status.name = new byte[4128]; getStatus(ref status); } 

However, calling refreshStatus gives me a System.AccessViolationException.

Can someone help me figure out how I can call this function in C ++ from C #?

+5
source share
2 answers

Your structure expects an array pointer; you are sorting an array. One side of the transaction expects to receive the address "Sesame Street 123," and you provide an exact copy of the apartment building at this address. This will not work.

For proper coding of the code, you must have a complete and deep understanding of memory management in C #. My advice is that you get the services of an expert.

+3
source

You can try using StringBuilder instead of byte [] and LPStr instead of ByValArray:

 public struct STATUSSTRUCT { public UInt64 nameLen; [MarshalAs(UnmanagedType.LPStr, SizeConst = 4128)] public StringBuilder name; } status = new STATUSSTRUCT(); status.nameLen = 4128; status.name = new StringBuilder(4128); getStatus(ref status); 

https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.unmanagedtype(v=vs.110).aspx

+2
source

All Articles