I've done a fair bit of research, but am stuck now as to why I'm still getting this error. I have a struct with the following attributes:
struct Account
{
//private attributes
private double mBalance;
private int mAccountNumber;
private string mName;
private string mDateCreated;
}
and am trying to do the following:
class BankManager
{
//private attributes
private unsafe Account *mAccounts;
private unsafe bool *mAccountsAvailable;
private int mNumberAccounts;
}
Even after turning my class Account to a struct, using "unsafe" for the attributes in class BankManager, and telling the compiler it can use unsafe code (in properties -> Build), I'm still getting this error at
*mAccounts
Any ideas as to why? I'm pretty sure all the types I'm using in the struct are legal to have pointers to in c#. Thanks in advance!
The strings in the Account class cause this problem. To understand why, you need to understand how the garbage collector works. It discovers garbage by tracking references to objects. The mName and mDateCreated are such references. The mBalance and mAccountNumber are not, those fields are value types. And, most importantly, the BankManager.mAccounts field is not, it is a pointer.
So the compiler can tell up front that the garbage collector will never be able to see the string references. Because the only way to do so is to go through the mAccount field and its not a reference.
The only cure for this is to limit yourself strictly to value types. The only way to do that for strings is to allocate them in unmanaged memory with, say, Marshal.StringToCoTaskMemUni() and store the IntPtr in the field. It is now out of reach from the garbage collector and cannot get moved by it. You'll now also have the burden of releasing that string.
Clearly that's not practical and prone to cause leaks, the kind of problem that's so common in C programs. Not sure why you are pursuing this at all but do keep in mind that a reference to an object is already a simple pointer so you are not gaining anything by using pointers yourself.
Strings are reference types in .NET and are non-blittable for struct pointers. See Blittable and Non-Blittable Types for a list of value types for what you want to do.
Unless you have special business requirements, you should stick with managed memory for maintainability and general sanity.
Use private unsafe fixed char mName[126];
Strings are managed types, and so are non-fixed arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With