如何将结构从C#传递到C ++ DLL?

Salocinx

好的,我的激光设备控制器的一系列问题还在继续...我想从我的C#代码中的DLL中调用以下C ++函数:

extern "C" _declspec(dllimport) int SendFrame(DWORD deviceIndex, byte* pData, DWORD numOfPoints, DWORD scanrate);

指针pData指向在C ++头文件中定义的一系列激光点,如下所示:

#pragma pack (1)
struct LaserPoint {
    WORD x;
    WORD y;
    byte colors[6];
};

在C#端,我将函数导入定义如下:

[DllImport("..\\..\\dll\\StclDevices.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int SendFrame(UInt32 deviceIndex, ref byte[] pData, UInt32 numOfPoints, UInt32 scanrate);

...和这样的LaserPoint结构:

[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct LaserPoint {
    public UInt16 x;
    public UInt16 y;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
    public byte[] colors;
}

然后我这样调用该SendFrame函数:

LaserPoint point = new LaserPoint();
point.x = 16384;
point.y = 32768;
point.colors = new byte[] {255, 0, 0, 0, 0, 0};

byte[] arr = point2array(points);
SendFrame(0, ref arr, 1, 30000);

这是我将LaserPointstruct实例转换为字节数组函数:

private static byte[] point2array(object obj) {
    int len = Marshal.SizeOf(obj);
    byte[] arr = new byte[len];
    IntPtr ptr = Marshal.AllocHGlobal(len);
    Marshal.StructureToPtr(obj, ptr, true);
    Marshal.Copy(ptr, arr, 0, len);
    Marshal.FreeHGlobal(ptr);
    return arr;
}

但是我的激光设备没有收到正确的输入,因为激光的行为非常奇怪。在C ++项目中使用相同的代码可以正常工作。因此,该C#互操作性代码存在该错误。

有任何想法吗?

火热

数组已经是引用类型,所以ref byte[]类似于byte**—失去了的双重间接寻址ref

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将结构传递到dll

如何将函数指针从C#传递到C ++ Dll?

执行C ++函数后,使用GCHandle崩溃将大量结构从C#统一脚本传递到C ++ dll

如何将位图传递给由Delphi在C#中编写的dll?

将struct *从C#传递到C ++ DLL

如何将结构数组从C ++ dll返回到C#

为什么将字符串从C#传递到C ++ dll会得到NULL?

将复杂的数据结构从C#传递到本机dll

如何从VB6应用程序将char参数传递到C DLL?

如何将C#中的二维数组传递给C ++ DLL?

如何将Unicode字符串从C#传输到C / C ++ DLL

C ++结构到Delphi Record dll调用

如何将字节数组从C#传递到外部DLL

从C ++ DLL到Delphi:如何将指向数据的指针从C ++ DLL传递到Delphi程序?

如何将返回指针从C ++ dll函数返回到C#

将SWIG包装的C ++ .dll集成到C#项目

如何将DOMDocument从VBA传递到C ++ dll

如何将参数传递给用C#编写的托管代码dll的自定义操作?

如何将整数从C#方法复制到本机C DLL函数

将C#结构传递给非托管C ++ DLL时出现SafeArrayTypeMismatchException

将字符串从DLL传递到C#

如何将COM对象从VBA传递到C ++ DLL

将结构(或类)从C ++ dll传递到C#(Unity 3D)

将var字符串从C ++传递到Delphi dll

C#从C DLL导入结构

将字符串从Fortran dll传递到C#

C#将指向结构(包含不可复制类型)的指针传递给非托管C ++ DLL

将字节数组从 C++ 非托管 dll 传递到 C# unity

如何将 unsigned short* 从 Visual-C++ DLL 传递到 VB.NET