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

2019-12-16 20:26发布

问题:

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;
};