将带有字符串数组的C#结构传递给c ++函数,该函数接受c#结构的void *和c#字符串数组的char **

时间:2013-07-15 13:00:39

标签: c# pinvoke

我想将带有字符串数组的 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-&gt;参数),第一个数组元素(“first”)被打印出来, 但是使用((char *)cmd_data_ptr-&gt;参数)[i],无法访问元素和上面提到的异常即将到来。

结构内存地址包含所有结构元素的地址,但是在从c ++访问数据时,它只访问字符串数组的第一个元素。

2 个答案:

答案 0 :(得分:3)

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public String[] Parameters;

是一个内联数组。匹配的C ++声明是:

char* Parameters[2];

但你正试图将它与:

相匹配
char** Parameters;

这完全不同。

您需要手动编组。在C#struct中声明ParametersIntPtr。然后使用Marshal.AllocHGlobal分配本机内存来保存指针数组。然后使用指向字符串的指针填充这些指针。

[StructLayout(LayoutKind.Sequential)]
public struct TestInfo
{
    public int TestId;
    public IntPtr Parameters;
}

static void Main(string[] args) // no need for unsafe
{
    TestInfo testInfo;
    testInfo.TestId = 1;
    testInfo.Parameters = Marshal.AllocHGlobal(2*Marshal.SizeOf(typeof(IntPtr)));
    IntPtr ptr = testInfo.Parameters;
    Marshal.WriteIntPtr(ptr, Marshal.StringToHGlobalAnsi("foo"));
    ptr += Marshal.SizeOf(typeof(IntPtr));
    Marshal.WriteIntPtr(ptr, Marshal.StringToHGlobalAnsi("bar"));
    TestAPI(ref testinfoObj);
    // now you want to call FreeHGlobal, I'll leave that code to you
}

另一种方法是使用固定的IntPtr []并将其放在testInfo.Parameters中。

答案 1 :(得分:1)

这实际上更像是David的答案的扩展/扩展,但这是结束自定义编组的一种方法:

public struct LocalTestInfo
{
    public int TestId;
    public IEnumerable<string> Parameters;

    public static explicit operator TestInfo(LocalTestInfo info)
    {
        var marshalled = new TestInfo
            {
                TestId = info.TestId, 
            };
        var paramsArray = info.Parameters
            .Select(Marshal.StringToHGlobalAnsi)
            .ToArray();
        marshalled.pinnedHandle = GCHandle.Alloc(
            paramsArray, 
            GCHandleType.Pinned);
        marshalled.Parameters = 
            marshalled.pinnedHandle.AddrOfPinnedObject();
        return marshalled;
    }
}

[StructLayout(LayoutKind.Sequential)]
public struct TestInfo : IDisposable
{
    public int TestId;
    public IntPtr Parameters;

    [NonSerialized]
    public GCHandle pinnedHandle;

    public void Dispose()
    {
        if (pinnedHandle.IsAllocated)
        {
            Console.WriteLine("Freeing pinned handle");
            var paramsArray = (IntPtr[])this.pinnedHandle.Target;
            foreach (IntPtr ptr in paramsArray)
            {
                Console.WriteLine("Freeing @ " + ptr);
                Marshal.FreeHGlobal(ptr);
            }
            pinnedHandle.Free();
        }
    }
}

注意我的测试我换了CDecl:

[DllImport(@"Test.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int TestAPI(ref TestInfo info);

另外我认为你在C ++方面有一个错字:

extern "C" 
__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);

    // char**, not char*
    char** paramsArray = ((char **)cmd_data_ptr->Parameters);
    for(int i = 0; i < 3; i++)
    {
        printf("value: %s \r\n",paramsArray[i]);
    }
    return 0;
}

试验台:

static void Main(string[] args)
{
    var localInfo = new LocalTestInfo()
    {
        TestId = 1,
        Parameters = new[]
        {
            "Foo", 
            "Bar",
            "Baz"
        }
    };
    TestInfo forMarshalling;
    using (forMarshalling = (TestInfo)localInfo)
    {
        TestAPI(ref forMarshalling);                
    }
}

反向编组操作符留给读者练习,但基本上看起来应该是显式TestInfo操作符的反转。