C#-方法的类型签名与PInvoke不兼容 [英] C# - Method's type signature is not PInvoke compatible
问题描述
我正在尝试在C#(2010)中使用VC ++(2003)dll 从C#调用dll方法时出现此错误 方法的类型签名与PInvoke不兼容"
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;
};
再次出现相同的错误! 我在这里想念什么? 谁能帮我Plzz
Yet again I get the same error! What am I missing here? Can anybody help me Plzz
推荐答案
您说您正在使用该结构作为返回值. 文档说:
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.
最简单的方法是通过函数的参数返回结构.更改C ++函数以接受类型为SLFData*
的参数,并使调用者传递C ++函数填充的结构的地址.在C#端,您将结构作为out
参数传递.
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,您的结构声明错误.首先,C#char
为两个字节宽.最好这样做:
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;
};
这篇关于C#-方法的类型签名与PInvoke不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!