all groups > dotnet interop > august 2007 >
You're in the

dotnet interop

group:

Retrieving a member's SizeConst value


Retrieving a member's SizeConst value MLM450 NO[at]SPAM hotmail.com
8/27/2007 7:22:22 AM
dotnet interop:
Is it possible to retrieve an item's "sizeconst" value dynamically?

I have the following member defined in a class:
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
private char[] units;

I want the code that values the units member to know the value of
SizeConst. I know I can define the size in another member but
accessing the SizeConst would make things much cleaner for what I am
trying to do.

Thanks,
Mike
Re: Retrieving a member's SizeConst value Mattias Sjögren
8/27/2007 10:00:59 PM

[quoted text, click to view]

Depends on which version of .NET you're using. In v1.x it was
nontrivial to do. As of 2.0 you should just have to use regular
Reflection and look for the MarshalAs attribute.


Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Re: Retrieving a member's SizeConst value Doug Semler
9/3/2007 4:13:11 PM
[quoted text, click to view]


Why? SizeConst (as hinted by the name) is a constant. You are telling the
marshaller that you will be marshalling a 5 element array. Everything
(including your initializer of units = new units[5]) must use that constant
size. If possible, I would also make the units member readonly (I can't
remember if this is possible with interop though).

For .NET code, you can use a

const int unitArraySize = 5;

and reference that value anywhere you need to know the size of the array:

[MarshalAs(UnmanagedType.ByValArray, SizeConst = unitArraySize)]
private char[] units = new units[unitArraySize];

void function
{
// I need to know the size. you can use unitArraySize, but I
personally would use units.Length.
}

--
Doug Semler, MCPD
a.a. #705, BAAWA. EAC Guardian of the Horn of the IPU (pbuhh).
The answer is 42; DNRC o-
Gur Hfrarg unf orpbzr fb shyy bs penc gurfr qnlf, abbar rira
erpbtavmrf fvzcyr guvatf yvxr ebg13 nalzber. Fnq, vfa'g vg?
AddThis Social Bookmark Button