How to call an external API function that takes a struct containing arrays as its parameter?

R

Robert Rossney

I'm working on a .NET application interoperates with a legacy application.
This application exposes an API through a single function call that takes a
great big struct full of string data as its argument.

In VB6, I can call the API by using these declarations:

Public Declare Sub MyApi Lib "MyApi.DLL" (buf As BUFFER_TYPE)

Public Type BUFFER_TYPE
foo As String * 50
bar(49) As String * 100
status As int
End Type

I'm trying to write the equivalent C#.Net code, and I *think* it should look
something like this:

[StructLayout (LayoutKind.Sequential)]

internal struct barString
{
[MarshalAs( UnmanagedType.AnsiBStr, SizeConst=100)]
internal string data;
}

internal struct buffer
{
[MarshalAs( UnmanagedType.AnsiBStr, SizeConst=50 )]
internal string foo;
[MarshalAs( UnmanagedType.ByValArray, SizeConst=49)]
internal barString bar[];
[MarshalAs (UnmanagedType.I2)]
internal int status;
}

[DllImport("MyApi.dll")]
private static extern void MyApi(buffer buf);

That is, in order for me to create a 49-element array of 100-byte strings
(bar), I first need to create a struct that's a 100-byte string, and then I
need to create an array of that struct that is dimensioned to 49 elements.

This seems awfully complicated. (Also, the real data structure is much more
complex than this, containing many arrays.) Is this really the right way to
do this?

In addition, this code:

buffer buf;
foreach (barString oneBar in buf.bar)
{
oneBar.data = "";
}

fails in the assignment statement with the message "The left-hand side of an
assignment must be a variable, property, or indexer." This leads me to
suspect that I'm not using structs properly, but for the life of me I can't
see why not.

Any ideas and pointers would be much appreciated. Thanks.

Bob Rossney
(e-mail address removed)
 

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

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,158
Latest member
Vinay_Kumar Nevatia
Top