gpt4 book ai didi

c# - 将 C++ 结构编码到 C#

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:40:40 25 4
gpt4 key购买 nike

我在非托管 C++ 中有这样简单的结构:

struct Cam
{
char ip[16];
char login[16];
char pass[16];
char name[16];
};

和 C# 编码结构:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct Cam
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string ip;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string login;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string pass;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string name;
}

当我通过函数将 C# 结构传递给 C++ 库时

[DllImport("NVRLib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void AddCameraStruct(Cam cam);
...
Cam cam = new Cam();
cam.ip = "192.168.0.232";
cam.login = "admin";
cam.pass = "admin";
cam.name = "kekekeke";
AddCameraStruct(cam);

并在 C++ 中打印传递的值:

__declspec(dllexport) void AddCameraStruct(Camera cam)
{
printf(cam.ip);
printf("\n");
printf(cam.login);
printf("\n");
printf(cam.name);
printf("\n");
printf(cam.pass);
strcpy(camera[CAM_NUM].ip, cam.ip);
strcpy(camera[CAM_NUM].login, cam.login);
strcpy(camera[CAM_NUM].pass, cam.pass);
strcpy(camera[CAM_NUM].name, cam.name);
CAM_NUM++;
}

它打印:

232
<EMPTY LINE>
192.168.0.232
n

我做错了什么?

最佳答案

在我从您的评论中了解到更多信息之后,

改变

__declspec(dllexport) void AddCameraStruct(Camera cam)

__declspec(dllexport) void AddCameraStruct(Cam cam)

关于c# - 将 C++ 结构编码到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23562038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com