Document directory
- Exception background
- Exception Analysis and Resolution
- Discover new problems
Exception background
This is a running error. The complete error message is as follows:
Test method ***. Tests. IpHelperTest. TestMarshalSize threw exception:
System. TypeLoadException: cocould not load type '***. Network. Protocol. ConnectionRequest' from assembly '***, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null' becauseThe format is invalid.
The code that causes the error is a unit test code:
[TestMethod]
publicvoid TestMarshalSize()
{
var size = Marshal.SizeOf(typeof(ConnectionRequest));
Assert.AreEqual(7, size);
}
ConnectionRequest is defined as follows:
[StructLayout(LayoutKind.Sequential, Pack =1, CharSet = CharSet.Ansi)]
publicclass ConnectionRequest:MessageBase
{
publicbyte ClassID;
public ProtocolVersion ProtocolVersion;
}
Exception Analysis and Resolution
Very simple code, but the error is confusing. At first, I thought the dll compilation settings were incorrect. For example, the test project was compiled to x64, but the tested code library was compiled to 32 bits. After the check, my project does not have this problem. In fact, the problem exists in the definition of the ConnectionRequest parent class. Let's take a look at the definition of MessageBase:
publicabstractclass MessageBase
{
public DataPacketHeader header;
}
I didn't define StructLayout for MessageRequest, because I don't plan to perform the Marshal operation on MessageBase. However, this does not seem to comply with C #'s requirements for Marshal operations,If you want to perform Marshal operations on a class, you must set StructLayout for its parent class.,Even if its parent class has nothing. To solve the problem of TypeLoadException, we need to set StructLayout for MessageBase.
Discover new problems
However, I found another problem: If a custom class does not explicitly inherit other classes, it will actually inherit the Object class. If the custom class needs to be Marshal, the Object class also needs to define StructLayout, but check the definition of the Object and find that StructLayout does not exist. What is this? I have not found any related documents.