gpt4 book ai didi

c# - Pinvoke Bool - MarshalDirectiveExeption

转载 作者:行者123 更新时间:2023-11-28 06:33:47 28 4
gpt4 key购买 nike

我想从具有 bool 属性的非托管代码返回一个结构:

EXTERN_C UA_EXPORT_WRAPPER_IMPORT DN_OPstruct DOTNET_GetOperation(){
DN_OPstruct op;
op.direction = true;
return op; }

struct DN_OPstruct{
bool direction; }

我的 C# 代码如下所示:

[StructLayout(LayoutKind.Sequential,Pack = 8, CharSet = CharSet.Ansi)]
public struct DN_OPstruct{
[MarshalAs(UnmanagedType.I1)]
bool direction; }

[DllImport("somedll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "somefct",
ExactSpelling = true, CharSet = CharSet.Ansi)]
public static extern DN_OPstruct DOTNET_GetOperation();

不幸的是我收到了这个错误信息:

An exception of type 'System.Runtime.InteropServices.MarshalDirectiveException' occurred in WindowsFormsApplication1 but was not handled in user code

附加信息:方法的类型签名与 PInvoke 不兼容。

如果有这个异常的处理程序,程序可以安全地继续。

最佳答案

如错误所述,该结构与 p/invoke 不兼容。函数返回值必须是 blittable 而那个类型不是。可在此处找到信息:http://msdn.microsoft.com/en-us/library/75dwhxf7.aspx

Structures that are returned from platform invoke calls must be blittable types. Platform invoke does not support non-blittable structures as return types.

同一主题继续列出可 blittable 的类型,bool 不在列表中。

您应该使用 byte 而不是 bool。你可以这样包装它:

[StructLayout(LayoutKind.Sequential)]
public struct DN_OPstruct
{
private byte _direction;
public bool direction
{
get { return _direction != 0; }
set { _direction = (byte)(value ? 1 : 0); }
}
}

我还要评论,Pack 的使用在这里似乎不正确,并且不需要在任何地方指定 CharSet

关于c# - Pinvoke Bool - MarshalDirectiveExeption,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27105915/

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