Link to home
Start Free TrialLog in
Avatar of jon_finch
jon_finch

asked on

Problem Marshalling a Byte Array in VB.Net

Hi All,

I am trying to store a font in the VB.Net and then read it back from the assembly and use this font in my application. Should be fairly straight forward IMO. I have stored the font in the Assembly okay so I am now trying to read it back.

I found some c# code to do this (as follows)

<code>
PrivateFontCollection fonts = new PrivateFontCollection();
Assembly asm = this.GetType().Assembly;
Stream stm = asm.GetManifestResourceStream("BarCodeFont.ttf");
byte[] buffer = new byte[stm.Length];
stm.Read(buffer, 0, (int)stm.Length);
IntPtr pi = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * buffer.Length);
Marshal.Copy(buffer, 0, pi, buffer.Length);
fonts.AddMemoryFont(pi, buffer.Length);
Marshal.FreeHGlobal(pi);
</code>

I have converted this code to VB.net as follows
<code>
Dim myFonts As New PrivateFontCollection()
Dim asm As [Assembly] = Me.GetType.Assembly
Dim stm As Stream = asm.GetManifestResourceStream("CreativeTools.FtraBk__.ttf")

Dim myBuffer(Convert.ToInt32(stm.Length)) As Byte
stm.Read(myBuffer, 0, Convert.ToInt32(stm.Length))
Dim pi As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(GetType(myBuffer)) * myBuffer.Length)
Marshal.Copy(buffer, 0, pi, myBuffer.Length)
myFonts.AddMemoryFont(pi, myBuffer.Length)
Marshal.FreeHGlobal(pi)
</code>

However, when I run this code I get a problem trying to use Marshal.SizeOf(GetType(myBuffer)).
I have also tried Marshal.SizeOf(myBuffer.getType) but I still get the following error:

--
Additional information: Type System.Byte[] can not be marshaled as an unmanaged structure; no meaningful size or offset can be computed.

--

I need to get the size of a byte and multiply this by the amount of elements in the byte array to get the exact memory needed for the font. I have been searching for ages and trying several different variation but all to no avail. I been told to use buffer.length but this will only give me the amount of elements in the byte array I still need to multiply this by the size of a byte to get the memory needed!

Any ideas would be greatly appreciated as time is extreamly short and this is my last stumbling block on this project.

All the best,

Jon

p.s.
Appologies if I've not formatted the code correctly but each board has their own ways of doing things an I'm new to this one ;)

Avatar of testn
testn

You can use just

Dim pi As IntPtr = Marshal.AllocHGlobal(myBuffer.Length)
ASKER CERTIFIED SOLUTION
Avatar of testn
testn

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial