Mit*_*ita 3 .net c c# pinvoke unmanaged
我在非托管C/C++代码(dll)中有一个函数,它返回一个包含char数组的结构.我创建了C#struct来接收调用该函数的返回值.并且调用此函数的uppon得到'System.Runtime.InteropServices.MarshalDirectiveException'
这是C声明:
typedef struct T_SAMPLE_STRUCT {
int num;
char text[20];
} SAMPLE_STRUCT;
SAMPLE_STRUCT sampleFunction( SAMPLE_STRUCT ss );
Run Code Online (Sandbox Code Playgroud)
这是C#声明:
struct SAMPLE_STRUCT
{
public int num;
public string text;
}
class Dllwrapper
{
[DllImport("samplecdll.dll")]
public static extern SAMPLE_STRUCT sampleFunction(SAMPLE_STRUCT ss);
}
Run Code Online (Sandbox Code Playgroud)
我使用1字节ASCII.
有没有人有关于如何做到这一点的提示或解决方案?
转换C数组成员的技巧是使用MarshalAs(UnmanagedType.ByValTStr).这可以用来告诉CLR将数组编组为内联成员与普通非内联数组.请尝试以下签名.
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet=System.Runtime.InteropServices.CharSet.Ansi)]
public struct T_SAMPLE_STRUCT {
/// int
public int num;
/// char[20]
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=20)]
public string text;
}
public partial class NativeMethods {
/// Return Type: SAMPLE_STRUCT->T_SAMPLE_STRUCT
///ss: SAMPLE_STRUCT->T_SAMPLE_STRUCT
[System.Runtime.InteropServices.DllImportAttribute("<Unknown>", EntryPoint="sampleFunction")]
public static extern T_SAMPLE_STRUCT sampleFunction(T_SAMPLE_STRUCT ss) ;
}
Run Code Online (Sandbox Code Playgroud)
此签名由CodePlex上提供的PInovke Interop Assistant(链接)提供给您.它可以自动将大多数PInvoke签名从本机代码转换为C#或VB.Net.