Jack Lee
Jack Lee

Reputation: 483

why there will be AccessViolationException when using struct rather than class

When I pass in a struct to some PInvoke method, I will receive the error

Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

When I use class, then it is OK.

I want to know any reason behind that?

Upvotes: 0

Views: 163

Answers (1)

haiyyu
haiyyu

Reputation: 2242

MSDN states in this article:

By default, native and managed structures are laid out differently in memory, so successfully passing structures across the managed/unmanaged boundary requires extra steps to preserve data integrity.

You will also find additional information that will come in handy when using PInvoke there.

Upvotes: 1

Related Questions