我用C / C ++编写了下一个函数:
__ declspec(dllexport)short CiBoardInfo(canboard_t * binfo);
宣布结构:
typedef struct {
unsigned char brdnum;
unsigned long hwver;
short chip[4];
char name[64];
char manufact[64];
} canboard_t;
我需要在C#中使用它,所以我试试这个:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct canboard_t{
public Byte brdnum;
public UInt32 hwver;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=4)]
public Int16 chip;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=64)]
public String name;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=64)]
public String manufact;
};
class Chai
{
[DllImport("chai.dll")]
public static extern Int16 CiInit();
[DllImport("chai.dll")]
public static extern Int16 CiBoardInfo(ref canboard_t binfo);
}
并试着像这样使用它:
private void Form1_Load(object sender, EventArgs e)
{
canboard_t brd = new canboard_t();
Chai.CiInit();
Chai.CiBoardInfo(ref brd);
this.Text = brd.manufact + " " + brd.name;
}
当用
调用Chai.CiBoardInfo(ref brd)时它会挂起System.TypeLoadException.TypeLoadException
那有什么不对?据我所知,我的C#代码中有不正确的书面结构。但我无法找到错误的位置。
1. ChaiVGSNAG2.exe!ChaiVGSNAG2.Program.Main() Line 18 + 0x1d bytes
2. [from machine code to managed]
3. [from managed code to machine]
4. mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile,
System.Security.Policy.Evidence assemblySecurity, string[] args) +
0x6b bytes
5. Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
+ 0x27 bytes
6. mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object
state) + 0x6f bytes
7. mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext
executionContext, System.Threading.ContextCallback callback, object
state, bool preserveSyncCtx) + 0xa7 bytes
8. mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext
executionContext, System.Threading.ContextCallback callback, object
state, bool preserveSyncCtx) + 0x16 bytes
9. mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext
executionContext, System.Threading.ContextCallback callback, object
state) + 0x41 bytes
10. mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x44
bytes
11. [from machine code to managed]