How to marshal C pointers to arrays in VB .NET

K

kevin

Hi
I have a C struct that is of the following

typedef struct{

DWORD num_conversions; ...

short *sample_values;

....

} DSCAIOINT;


In VB I'm doing the following


<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi, Pack:=1)> _

Public Structure DSCAIOINT

....

Public num_conversions As Integer

....

Public sample_values() As Short

End Structure



in my code I'm passing my DSCAIOINT structure as

Public Declare Function dscADSampleInt Lib "a.dll" ( ByRef dscaioint As
DSCAIOINT) As Byte

However I'm not sure how to marshal the sample_values array so it will be a
short pointer. VB .NET keeps giving me errors of 'System.TypeLoadException'

"Additional information: Can not marshal field sample_values of type
ADSampleInt.DSCAIOINT: This type can not be marshaled as a structure field."

Can any one give me some help? thank you!
 
I

Imran Koradia

Define sample_values as IntPtr and use Marshal.Copy to retrieve the data.

Public Structure DSCAIOINT
Public num_conversions As Integer

....

Public sample_values As IntPtr

End Structure

Public Declare Function dscADSampleInt Lib "a.dll" ( _
ByRef dscaioint As DSCAIOINT) As Byte

Dim myStruct As DSCAIOINT
Dim BUFF_SIZE = 2048

myStruct.sample_values = Marshal.Alloc(SizeOf(Short)*BUFF_SIZE)

Dim Result As Byte = dscADSampleInt(myStruct)

Dim samples(BUFF_SIZE) As Short

Marshal.Copy(myStruct.sample_values, samples, 0, BUFF_SIZE)


hope that helps..
Imran.
 
K

kevin

Hi Imran
You are a genius! Thanks for the help. I had to use Marshal.AllocHGlobal
but everything works. Thanks for your help!

--
Kevin Liu
Imran Koradia said:
Define sample_values as IntPtr and use Marshal.Copy to retrieve the data.

Public Structure DSCAIOINT
Public num_conversions As Integer

....

Public sample_values As IntPtr

End Structure

Public Declare Function dscADSampleInt Lib "a.dll" ( _
ByRef dscaioint As DSCAIOINT) As Byte

Dim myStruct As DSCAIOINT
Dim BUFF_SIZE = 2048

myStruct.sample_values = Marshal.Alloc(SizeOf(Short)*BUFF_SIZE)

Dim Result As Byte = dscADSampleInt(myStruct)

Dim samples(BUFF_SIZE) As Short

Marshal.Copy(myStruct.sample_values, samples, 0, BUFF_SIZE)


hope that helps..
Imran.
 
I

Imran Koradia

I had to use Marshal.AllocHGlobal but everything works.
Oops..sorry - thats what I meant. There's no Alloc method in the Marshal
class..
Thanks for your help!
glad to help :)


Imran.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top