I want to send a C# structure with string array to a C++ function which accepts void * for the c# structure and char** for the c# structure string array member.
I was able to send the structure to c++ function,but the issue is , not able to access the string array data member of c# structure from c++ function. When sending the string array separately,i was able to access the array elements.
Sample code is-
C# Code:
[StructLayout(LayoutKind.Sequential)]
public struct TestInfo
{
public int TestId;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public String[] Parameters;
}
[DllImport("TestAPI.dll", CallingConvention = CallingConvention.StdCall, EntryPoint "TestAPI")]
private static extern void TestAPI(ref TestInfo data);
static unsafe void Main(string[] args)
{
TestInfo testinfoObj = new TestInfo();
testinfoObj.TestId = 1;
List<string> names = new List<string>();
names.Add("first");
names.Add("second");
names.Add("third");
testinfoObj.Parameters=names.ToArray();
TestAPI(ref testinfoObj);
}
VC++ Code:
/*Structure with details for TestInfo*/
typedef struct TestInfo
{
int TestId;
char **Parameters;
}TestInfo_t;
//c++ function
__declspec(dllexport) int TestAPI(void *data)
{
TestInfo *cmd_data_ptr= NULL;
cmd_data_ptr = (TestInfo) data;
printf("ID is %d \r\n",cmd_data_ptr->TestId);//Working fine
for(i = 0; i < 3; i++)
printf("value: %s \r\n",((char *)cmd_data_ptr->Parameters)[i]);/*Error-Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt*/
}
When analyzing the memory stack, it is observed that,when i print ((char *)cmd_data_ptr->Parameters), the first array element("first") is getting printed, but using ((char *)cmd_data_ptr->Parameters)[i], not able access elements and above mentioned exception is coming.
The structure memory address contains address of all the structure elements,but while accessing the data from c++,it is accessing only the first element of the string array.