从c#到c++的互操作传递结构
interop pass structure from c# to c++
c#代码:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct Message
{
public uint MsgId;
public uint DLC;
public uint Handle;
public uint Interval;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] Data;
};
我必须将这个结构发送到c++native.dll中的一个函数,如下所示:
[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U4)]
public static extern int AFT_iSetRTSECANWrapper(IntPtr Data);
我正在准备这样的缓冲区:
Message frame = new Message();
frame.MsgId = (uint)MsgId;
frame.DLC = (uint)DLC;
frame.Interval = (uint)Interval;
frame.Data = new byte[64];
for (int i = 0; i < Data.Length; i++)
{
frame.Data[i] = 11;
}
//Transmit message
int rawsize = Marshal.SizeOf(frame);
IntPtr frameBuffer = Marshal.AllocHGlobal(rawsize);
Marshal.StructureToPtr(frame, frameBuffer, false);
AFT_iSetRTSECANWrapper(frameBuffer);
在c++中,i具有以下结构:
typedef struct {
unsigned int MsgId;
unsigned int DLC;
unsigned int Handle;
unsigned int Interval;
unsigned char Data[64];
} Message;
要调用的函数是:
extern "C" __declspec(dllexport) int AFT_iSetRTSECANWrapper(Message *data)
在这之后,我只是尝试访问消息中的字段与数据->DLC,但我一无所获。我搞不清楚这里出了什么问题。
我猜数据没有分配在与结构的其他部分相同的连续部分中,因此不会跨区域传输。尝试
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct Message
{
public uint MsgId;
public uint DLC;
public uint Handle;
public uint Interval;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public byte[] Data = new byte[64];
};
对于C++位,而不是传输到intptr,直接传输
[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U4)]
public static extern int AFT_iSetRTSECANWrapper([in,out] Message Data);
以发送您的消息
Message frame = new Message();
frame.MsgId = (uint)MsgId;
frame.DLC = (uint)DLC;
frame.Interval = (uint)Interval;
for (int i = 0; i < Data.Length; i++)
{
frame.Data[i] = 11;
}
//Transmit message
AFT_iSetRTSECANWrapper(frame);
相关文章:
- 如何读取 C++ SAFEARRAY**,该 SAFEARRAY** 是 COM 互操作的结果,其中 C# 返回值为
- 编译为 wasm 的 C++ 和 Rust 程序可以以某种方式互操作吗?
- 有什么语言可以与C++互操作吗
- 使 Flutter C/C++ 互操作示例正常工作
- C++互操作(隐式 PInvoke)的限制
- COM 互操作结构定义与内存布局不匹配
- _Complex 和 std::complex 之间的 C/C++ 互操作
- C# COM 服务器互操作 - System.InvalidCastException.
- 从C++与 C 灵活阵列成员互操作的正确方法是什么?
- 如何通过 COM 互操作访问复杂对象的属性?
- 如何区分"QObject"的亲子关系关注点,例如与其他所有者进行互操作?
- DirectWrite GDI 互操作:使用"IDWriteFontFace"绘制文本的简单方法
- opencl openGL互操作内核参数用于读取 写入
- Rust 互操作与 C++ std::string
- 以结构格式操作数据最终会变得很奇怪
- 将互操作 HwndSource 包装在 c++/cli 中,以用于本机 c++/MFC 应用程序
- 跨 C# 和 COM 互操作使用对象C++
- 尝试为c++互操作自动生成库时出错
- 从c#到c++的互操作传递结构
- 通过互操作调用方法,该方法返回结构的实例