c# - 将指向结构数组指针的指针从 C# 传递到 C++

标签 c# c++ pinvoke marshalling unmanaged

我想将指向结构数组指针的指针从 C# 传递到 C++。使用以下代码,我只获取 C++ 中的第一个元素,不传递数组的第二个和第三个元素。为什么?此外,尝试使用 StructureToPtr 但没有帮助。我做错了什么?

C++代码

 struct structure 
{
   short ps;

};
   __declspec(dllexport)short Testmethod(structure** aa)
    {
     if (aa!= 0 && aa[0]->ps == 26 && aa[1]->ps == 27)
     {          
        return 1;
      }    
      return  0;
    }

C#代码

[DllImport("Wrapper.dll", CallingConvention = CallingConvention.Cdecl)]
public unsafe static extern short Testmethod(ref IntPtr a);

     [StructLayout(LayoutKind.Sequential)]           
     public struct SampleStructure
    {
       public short ps;

    };

 SampleStructure[] data= new SampleStructure[3] { new SampleStructure { ps = 26 }, new SampleStructure { ps = 27 }, new SampleStructure { ps = 28 } };
                        GCHandle gch = GCHandle.Alloc(data, GCHandleType.Pinned);
                        IntPtr ptr = gch.AddrOfPinnedObject();
                        ret = Testmethod(ref ptr);

我无法更改 C++ 代码,我无权访问它。如果将 c++ 代码更改为以下任一方式,它就可以工作。如何在不更改 C++ 代码的情况下实现它? 更新:

方法 1: 如果我更改 C++ 代码,则有效。但我无法更改 C++ 代码。这不是我的代码。

C++ 代码

__declspec(dllexport)short Testmethod(structure* aa)

C#代码

            fixed (SampleStructure* pArray = dataInformation)
            {
                ret = Testmethod(pArray);
            }

方法 2: 如果我更改 C++ 代码,则有效。但我无法更改 C++ 代码。这不是我的代码。

C++ 代码

__declspec(dllexport)short Testmethod(structure Getcsharpval[], int size)

c#代码

 public unsafe static extern short Testmethod([MarshalAs(UnmanagedType.LPArray,SizeParamIndex=3)] SampleStructure[] array);
 SampleStructure[] data= new SampleStructure[3] { new SampleStructure { ps = 26 }, new SampleStructure { ps = 27 }, new SampleStructure { ps = 28 } };
 ret = Testmethod( data);

最佳答案

我认为你的 c 函数有错误的原型(prototype)。 尝试:

_declspec(dllexport)short Testmethod(structure* aa)
{

    if (aa != 0
       && aa[0].ps == 26 && aa[1].ps == 27)

    {
        return 1;
    }

    return 0;
}

在您的 C# 示例中,您有一个结构数组。该数组是引用类型,您更正需要固定内存。该数组是值类型(并且不需要引脚)的结构内存中的序列。所以在数组中你没有指针,而是直接的结构。

关于c# - 将指向结构数组指针的指针从 C# 传递到 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36093750/

相关文章:

c# - 将具有枚举成员的非托管结构编码到 c#

c# - XAML 页面未在 Windows 10 Mobile 上的 WinRT 应用程序中被垃圾收集,但在 WP8.1 上按预期工作

C# 从外部 dll 读取 web.config 中的 <system.net><mailSettings>

C#帮助序列化

c++ - 如何检查 AVX intrinsic __m256 的 inf

.net - 是否可以在 .net 中捕获/重定向我未启动的进程的标准输出?

c# - 从 C# 向进程发送 CTRL_C/SIGINT

C# - 应用程序全屏并阻止 Windows native 键盘命令

c++ - Windows 构建系统 : How to build a project (from its source code) which doesn't have *. sln 或 Visual C++ 项目文件 (*.vcproj)

c++ - 限制函数执行时间