处理此结构和方法的正确 C# 互操作代码是什么?
我正在围绕非托管 DLL 编写托管包装器,但无法正确编组以下方法和结构。以下是 .h 文件中非托管代码的内容:
typedef struct {
WORD PI_code;
DWORD grpStat[31];
BYTE PTY_code;
char* PS;
char* RT;
} RdsData_t;
COMPANYNAME_API void COMPANY_get_rds_data(RdsData_t* rds_data);
以下是我在 PInvoke Interop Assistant 的帮助下得出的结论:
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct RdsData_t
{
/// WORD->unsigned short
public ushort PI_code;
/// DWORD[31]
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 31, ArraySubType = UnmanagedType.U4)]
public uint[] grpStat;
/// BYTE->unsigned char
public byte PTY_code;
/// char*
[MarshalAsAttribute(UnmanagedType.LPStr)]
public string PS;
/// char*
[MarshalAsAttribute(UnmanagedType.LPStr)]
public string RT;
}
[DllImport("companyname.dll", EntryPoint = "?COMPANYNAME_get_rds_data@@YAXPAURdsData_t@@@Z")]
private static extern void COMPANYNAME_get_rds_data(ref RdsData_t data);
但是,按原样调用时会抛出 AccessViolationException。通过搜索和实验,我能够想出一些不会引发异常的东西,但随后数据不正确或丢失,使我相信这些也不正确。
我应该为上述结构使用什么互操作代码?除了 PInvoke Assistant 之外,还有其他工具可以帮助我吗?
提前致谢!
I am writing a managed wrapper around an unmanaged DLL, and am unable to get the following method and structure to marshal correctly. Here's what's in the .h file for the unmanaged code:
typedef struct {
WORD PI_code;
DWORD grpStat[31];
BYTE PTY_code;
char* PS;
char* RT;
} RdsData_t;
COMPANYNAME_API void COMPANY_get_rds_data(RdsData_t* rds_data);
and here's what I've come up with, with some help from PInvoke Interop Assistant:
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct RdsData_t
{
/// WORD->unsigned short
public ushort PI_code;
/// DWORD[31]
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 31, ArraySubType = UnmanagedType.U4)]
public uint[] grpStat;
/// BYTE->unsigned char
public byte PTY_code;
/// char*
[MarshalAsAttribute(UnmanagedType.LPStr)]
public string PS;
/// char*
[MarshalAsAttribute(UnmanagedType.LPStr)]
public string RT;
}
[DllImport("companyname.dll", EntryPoint = "?COMPANYNAME_get_rds_data@@YAXPAURdsData_t@@@Z")]
private static extern void COMPANYNAME_get_rds_data(ref RdsData_t data);
However, as-is this throws an AccessViolationException when called. Through searching, and experimentation, I am able to come up with something that does not throw an exception, but then the data is incorrect or missing, leading me to believe those are not correct either.
What interop code should I use for the above struct? Are there any tools besides PInvoke Assistant that I could use to help me?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试以下
注意:但是,您需要允许您的库/应用程序执行不安全的代码才能使其正常工作。
Try the following
Note: however, you will need to allow your library/app to execute unsafe code in order for that to work.