C# - Method's type signature is not PInvoke compatible

岁酱吖の 提交于 2020-01-17 15:41:12

问题


I am trying to use the VC++ (2003) dll in C# (2010) When am calling the method of dll from c# am getting this error "Method's type signature is not PInvoke compatible"

I am returning the structure from VC++
Code:
struct SLFData
{
public:
char ByLat[10];
char ByLong[10];
};

And I am marshalling in C# 
Code:
 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct SLFData
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
        public char[] ByLat;     
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
        public char[] ByLong;
    };

Yet again I get the same error! What am I missing here? Can anybody help me Plzz


回答1:


You say that you are using the struct as a return value. The documentation says:

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

Your struct is not blittable. So you cannot use it as a function return type.

The simplest way to proceed is to return the struct via a parameter of the function. Change the C++ function to accept a parameter of type SLFData* and have the caller pass in the address of a struct which the C++ function populates. On the C# side you pass the struct as an out parameter.

FWIW, your struct declaration is wrong. For a start C# char is two bytes wide. It's best done like this:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SLFData
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
    public string ByLat;     
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
    public string ByLong;
};


来源:https://stackoverflow.com/questions/27201996/c-sharp-methods-type-signature-is-not-pinvoke-compatible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!