我想将带有字符串数组的 C# 结构发送到 C++ 函数,该函数接受 c# 结构的 void * 和 c# 结构字符串数组成员的 char**。
我能够将结构发送到 c++ 函数,但问题是,无法从 c++ 函数访问 c# 结构的字符串数组数据成员。单独发送字符串数组时,我能够访问数组元素。
示例代码是 -
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*/
}
在分析内存堆栈时,观察到,当我打印((char *)cmd_data_ptr->Parameters)时,第一个数组元素(“first”)正在打印,但使用((char *)cmd_data_ptr->Parameters) [i],无法访问元素和上述异常即将到来。
结构体内存地址包含所有结构体元素的地址,但是从c++访问数据时,它只访问字符串数组的第一个元素。